Home Php C# Sql C C++ Javascript Python Java Go Android Git Linux Asp.net Django .net Node.js Ios Xcode Cocoa Iphone Mysql Tomcat Mongodb Bash Objective-c Scala Visual-studio Apache Elasticsearch Jar Eclipse Jquery Ruby-on-rails Ruby Rubygems Android-studio Spring Lua Sqlite Emacs Ubuntu Perl Docker Swift Amazon-web-services Svn Html Ajax Xml Java-ee Maven Intellij-idea Rvm Macos Unix Css Ipad Postgresql Css3 Json Windows-server Vue.js Typescript Oracle Hibernate Internet-explorer Github Tensorflow Laravel Symfony Redis Html5 Google-app-engine Nginx Firefox Sqlalchemy Lucene Erlang Flask Vim Solr Webview Facebook Zend-framework Virtualenv Nosql Ide Twitter Safari Flutter Bundle Phonegap Centos Sphinx Actionscript Tornado Register | Login | Edit Tags | New Questions | 繁体 | 简体


10 questions online user: 4

0
votes
answers
25 views
+10

基於內容而不是位置在某些項目的列表視圖中開始一個新的活動或意圖

0

我想知道是否有可能在列表視圖中有可點擊的項目開始一個新的活動或意圖基於內容的項目而不是位置。每個特定的項目都需要具有特定的具體操作,我希望我的應用能夠將項目從列表視圖中的頂部或底部移動或將它們添加到新列表中。如果物品是靜止的,那麼將動作放在物品的位置上就可以正常工作,但由於物品會移動,所以會產生問題。因此,根據項目內容(此時的字符串)採取行動是最好的選擇,因爲它可以在項目所在的位置工作。基於內容而不是位置在某些項目的列表視圖中開始一個新的活動或意圖

目前,我使用的是if (item_position==1),if (item_position==2),如果(item_position==3)等。下面是引用的完整代碼:

public class MainActivity extends AppCompatActivity { 

    ArrayList<String> selectedItems; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     selectedItems = new ArrayList<String>(); 
     ListView chl = (ListView) findViewById(R.id.colorselector); 
     chl.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 
     String[] items = {"Blue", "Green", "Yellow", "White", "Black", "Grey"}; 
     Adapter adapter=new Adapter(this,items); 
     chl.setAdapter(adapter); 

     chl.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { 

       int item_position=i; 
       if (item_position==1){ 

       } 
+0

我想你可能需要有關的ListView一些更多的教程。我的博客關於listview:http://programandroidlistview.blogspot.com/。希望有所幫助! –

沙发
0
0

試試這個代碼

public class MainActivity extends AppCompatActivity { 

ArrayList<String> selectedItems; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    selectedItems = new ArrayList<String>(); 
    ListView chl = (ListView) findViewById(R.id.colorselector); 
    chl.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 
    String[] items = {"Blue", "Green", "Yellow", "White", "Black", "Grey"}; 
    Adapter adapter=new Adapter(this,items); 
    chl.setAdapter(adapter); 

    chl.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { 

      if(view instance of TextView){ 
       TextView textView=(TextView)view; 
       String data=textView.getText(); 

       if(data.equal("Blue")){ 


       }else if(data.equals("Green")){ 


       } 

      } 




     }};  
+0

謝謝,但我收到錯誤「不兼容類型」。必需:字符串,找到:字符序列。我改變了它,但它不起作用 - 當我點擊項目 – Fgf567

+0

textView.getText()。toString(); –

+0

現在它說不能解決方法「等於」 – Fgf567

板凳
0
0

可以使用這樣的檢索來自適配器點擊項目:

String clickedItem = adapterView.getAdapter().getItem(position); 

我假設您的適配器所持有的物品是String秒。您可能需要將項目轉換爲String

String clickedItem = (String) adapterView.getAdapter().getItem(position); 

或鑄Adapter您的具體實現適配器:

String clickedItem = ((MyAdapter)adapterView.getAdapter()).getItem(position); 
+0

@ Fgf567看起來該項目是「CharSequence」類型。你只需要將它轉換爲'CharSequence'而不是'String',(例如:'CharSequence clickedItem =(CharSequence)adapterView.getAdapter()。getItem(position);') – Titus

0
votes
answers
20 views
+10

如何更改由ArrayAdapter生成的TextView中的文本顏色

0

我正在使用帶有ArrayAdapter的ListView,並且我想在用戶單擊它時更改TextView內部文本的顏色。這工作正常,除非當一個TextView更改顏色另一個更下面的列表更改顏色了。如何更改由ArrayAdapter生成的TextView中的文本顏色

這是否與ArrayAdapter重用視圖有關?

ArrayAdapter<String> adapter = new ArrayAdapter<> (thisContext, R.layout.textview_1, arrayList); 
listView.setAdapter (adapter); 

listView.setOnItemClickListener (new AdapterView.OnItemClickListener() 
{ 
    @Override 
    public void onItemClick (AdapterView<?> parent, View view, int position, long id) 
    { 
     TextView textToChange = (TextView) view; 
     textToChange.setTextColor (Color.RED); 
    } 
}); 
+0

你需要採取'position'進去......你在做整個'view'的變化。 – DigitalNinja

沙发
0
1

這是否有東西做ArrayAdapter重用的看法?

是的。

您可以通過覆蓋getView()當您創建ArrayAdapter,做這樣的事情解決這個問題:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(thisContext, R.layout.textview_1, arrayList) { 

    @NonNull 
    @Override 
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { 
     // TODO 
    } 
}; 

你如何真正去解決這將取決於你想要什麼樣的行爲。這似乎是你的項目意見TextView真的,所以你可以像這樣的東西替換TODO:

TextView tv = (TextView) super.getView(position, convertView, parent); 
tv.setTextColor(Color.BLACK); 
return tv; 

這將確保任何回收的觀點有黑色文本,但它也意味着,如果你點擊在一行上(所以它變成紅色),將該行從視圖中滾動出來,然後再滾動回查看,它會變回黑色。

也許你可以更新存儲從OnItemClickListener內最後一次點擊的位置的變量,然後引用在getView()

TextView tv = (TextView) super.getView(position, convertView, parent); 
tv.setTextColor(position == lastClickedPosition ? Color.RED : Color.BLACK); 
return tv; 
0
votes
answers
14 views
+10

獲取ListView中選定項目

0

的價值觀我有這樣的ListView適配器:獲取ListView中選定項目

public class UpicksAdapter extends BaseAdapter 
{ 
    Context context; 

    List<Upick> upick_list; 

    public UpicksAdapter(List<Upick> listValue, Context context) 
    { 
     this.context = context; 
     this.upick_list = listValue; 
    } 

    @Override 
    public int getCount() 
    { 
     return this.upick_list.size(); 
    } 

    @Override 
    public Object getItem(int position) 
    { 
     return this.upick_list.get(position); 
    } 

    @Override 
    public long getItemId(int position) 
    { 
     return position; 
    } 



    @Override 
    public View getView(int position, View convertView, ViewGroup parent) 
    { 
     ViewItem viewItem = null; 
     if(convertView == null) 
     { 
      viewItem = new ViewItem(); 

      LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); 

      convertView = layoutInfiater.inflate(R.layout.listview_items, null); 

      viewItem.SubNameTextView = (TextView)convertView.findViewById(R.id.SubjectNameTextView); 

      viewItem.SubFullFormTextView = (TextView)convertView.findViewById(R.id.SubjectFullFormTextView); 
      convertView.setTag(viewItem); 
     } 
     else 
     { 
      viewItem = (ViewItem) convertView.getTag(); 
     } 

     viewItem.SubNameTextView.setText(upick_list.get(position).Subject_Name); 

     viewItem.SubFullFormTextView.setText(upick_list.get(position).Subject_Full_Form); 

     return convertView; 
    } 
} 


class ViewItem 
{ 
    TextView SubNameTextView; 
    TextView SubFullFormTextView; 
} 

ListView控件是一個片段。

我需要從listview選定的項目中獲取數據。我有這個聽衆:

UpicksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> parent, View view, int position, 
            long id) { 

       String item = UpicksListView.getItemAtPosition(position).toString(); 

       Log.d("VALOR","VALOR "+item); 



      } 
     }); 

我怎樣才能得到所選項目的值?

編輯:

完整的分段代碼:

public class MisUpicksFragment extends Fragment { 
    // TODO: Rename parameter arguments, choose names that match 
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER 
    private static final String ARG_PARAM1 = "param1"; 
    private static final String ARG_PARAM2 = "param2"; 



    private SessionManager session; 
    private ProgressDialog loading; 
    private EditText txtbusqueda; 
    private Button botonbuscar,botonrefrescar; 

    //movies 
    private static final String TAG = MainActivity.class.getSimpleName(); 
    public List<Upick> upicks; 
    private RecyclerView recyclerView; 
    private GridLayoutManager gridLayout; 
    private UpicksAdapter adapter; 


    // TODO: Rename and change types of parameters 
    private String mParam1; 
    private String mParam2; 
    private String user_id; 
    private Button btnNew; 




    ListView UpicksListView; 
    ProgressBar progressBar; 
    String HttpURL = "http://***/upicks_todos.php"; 
    private OnFragmentInteractionListener mListener; 

    public MisUpicksFragment() { 
     // Required empty public constructor 
    } 

    /** 
    * Use this factory method to create a new instance of 
    * this fragment using the provided parameters. 
    * 
    * @param param1 Parameter 1. 
    * @param param2 Parameter 2. 
    * @return A new instance of fragment MensajesFragment. 
    */ 
    // TODO: Rename and change types and number of parameters 
    public static MisUpicksFragment newInstance(String param1, String param2) { 
     MisUpicksFragment fragment = new MisUpicksFragment(); 
     Bundle args = new Bundle(); 
     args.putString(ARG_PARAM1, param1); 
     args.putString(ARG_PARAM2, param2); 
     fragment.setArguments(args); 
     return fragment; 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     if (getArguments() != null) { 
      mParam1 = getArguments().getString(ARG_PARAM1); 
      mParam2 = getArguments().getString(ARG_PARAM2); 
     } 

    } 



    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 






     View view = inflater.inflate(R.layout.fragment_misupicks, container, false); 





     UpicksListView = (ListView) view.findViewById(R.id.UpicksListView); 

     progressBar = (ProgressBar) view.findViewById(R.id.ProgressBar1); 

     new ParseJSonDataClass(getActivity()).execute(); 


     UpicksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> parent, View view, int position, 
            long id) { 

       String item = UpicksListView.getItemAtPosition(position).toString(); 



       Log.d("VALOR","VALOR "+item); 



      } 
     }); 





     return view; 
    } 


    private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> { 
     public Context context; 
     String FinalJSonResult; 
     List<Upick> upickFullFormList; 

     public ParseJSonDataClass(Context context) { 

      this.context = context; 
     } 

     @Override 
     protected void onPreExecute() { 

      super.onPreExecute(); 
     } 

     @Override 
     protected Void doInBackground(Void... arg0) { 

      HttpServiceClass httpServiceClass = new HttpServiceClass(HttpURL); 

      try { 
       httpServiceClass.ExecutePostRequest(); 

       if (httpServiceClass.getResponseCode() == 200) { 

        FinalJSonResult = httpServiceClass.getResponse(); 

        if (FinalJSonResult != null) { 

         JSONArray jsonArray = null; 
         try { 

          jsonArray = new JSONArray(FinalJSonResult); 
          JSONObject jsonObject; 
          Upick upick; 

          upickFullFormList = new ArrayList<Upick>(); 

          for (int i = 0; i < jsonArray.length(); i++) { 

           upick = new Upick(); 

           jsonObject = jsonArray.getJSONObject(i); 

           upick.Subject_Name = jsonObject.getString("id_servicio"); 

           upick.Subject_Full_Form = jsonObject.getString("cliente_servicio"); 

           upickFullFormList.add(upick); 
          } 
         } catch (JSONException e) { 
          // TODO Auto-generated catch block 
          e.printStackTrace(); 
         } 
        } 
       } else { 

        Toast.makeText(context, httpServiceClass.getErrorMessage(), Toast.LENGTH_SHORT).show(); 
       } 
      } catch (Exception e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) 

     { 
      progressBar.setVisibility(View.GONE); 

      UpicksListView.setVisibility(View.VISIBLE); 

      if (upickFullFormList != null) { 

       UpicksAdapter adapter = new UpicksAdapter(upickFullFormList, context); 

       UpicksListView.setAdapter(adapter); 
      } 
     } 
    } 


    private void logoutUser() { 
     session.setLogin(false); 



     // Launching the login activity 
     Intent intent = new Intent(getActivity(), LoginActivity.class); 
     startActivity(intent); 
     //finish(); 
    } 



    @Override 
    public void onDetach() { 
     super.onDetach(); 
     mListener = null; 
    } 

    /** 
    * This interface must be implemented by activities that contain this 
    * fragment to allow an interaction in this fragment to be communicated 
    * to the activity and potentially other fragments contained in that 
    * activity. 
    * <p> 
    * See the Android Training lesson <a href= 
    * "http://developer.android.com/training/basics/fragments/communicating.html" 
    * >Communicating with Other Fragments</a> for more information. 
    */ 
    public interface OnFragmentInteractionListener { 
     // TODO: Update argument type and name 
     void onFragmentInteraction(Uri uri); 
    } 


} 
+0

你傳遞給listview適配器的ArrayList的名稱是什麼? 顯示我的代碼也 –

沙发
0
1

更改此代碼制定者。

upick.Subject_Name = jsonObject.getString("id_servicio"); 
upick.Subject_Full_Form = jsonObject.getString("cliente_servicio"); 

如:

upick.setSubjectname(jsonObject.getString("id_servicio")); 
內的onclick可以使用干將

String item = upicks.get(position).getSubjectname(); 

parent.getItemAtPosition(position)會返回一個對象(在適配器中使用的模型)。爲了得到一些領域採取值

然後從你的Object不要調用Object.toString();它將返回對象引用而不是您正在查找的值。使用Object.yourField;代替。

+0

列表視圖適配器從JSON數組填充 – mvasco

+0

您是否希望我在我的問題中包含所有片段代碼? – mvasco

+0

@mvasco是的。那麼它會更清晰 –

板凳
0
1

The ArrayList.get() method is used to get the element of a specified position within the list.

String str_ITEM= upicks.get(position).yourGETMETHOD(); 
地板
0
0

在回調監聽你適配器對象只是使用像下面。

UpicksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> parent, View view, int position, 
            long id) { 

       String item = parent.getSelectedItem().toString(); 

       Log.d("VALOR","VALOR "+item); 

      } 
     }); 
0
votes
answers
41 views
+10

如何在add()命令中設置listview?

-2

如何在add()命令中設置listview? 首先這是代碼(不是真正的代碼)如何在add()命令中設置listview?

API_Interface.java

public interface API_Interface{ 
    @GET("/api/{buzz}") 
    Call<Buzz> Buzz_API(@Path("buzz") String buzz); 
} 

Buzz.java

public class Buzz{ 
    @SerializedName("buzz") 
    @Expose 
    private String buzz; 

    public String getBuzz() { 
     return buzz; 
    } 

    public void setBuzz(String buzz) { 
     this.buzz = buzz; 
    } 
} 

MainActivity.class

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_list_main); 

     ListView listView = (ListView) findViewById(R.id.list_view); 
     BuzzArrayList<Buzz> buzzArrayList = new BuzzArrayList<Buzz>(); 
     BuzzAdapter buzzAdapter = new BuzzAdapter(this, 0, buzzArrayList); 
     listView.setAdapter(buzzAdapter); 

     Retrofit buzz_retro = new Retrofit.Builder() 
      .baseUrl("https://buzz.com") 
      .addConverterFactory(GsonConverterFactory.create()) 
      .build(); 

     API_Interface buzz_service = buzz_retro.create(API_Interface.class); 

     //Get data 
     Call<Buzz> buzz1 = buzz_service.buzz_API("Apple"); 
     buzz1.enqueue(new Callback<Buzz>() { 
     @Override 
     public void onResponse(Call<Buzz> call, Response<Buzz> response) { 
      String buzz_1 = response.body().getBuzz(); //buzz_1="Apple" 
      buzzArrayList.add(new Exchange(buzz_1)); 
      buzzAdapter.notifyDataSetChanged(); 
      } 
     }); 

     Call<Buzz> buzz2 = buzz_service.buzz_API("Banana"); 
     buzz2.enqueue(new Callback<Buzz>() { 
     @Override 
     public void onResponse(Call<Buzz> call, Response<Buzz> response) { 
      String buzz_2 = response.body().getBuzz(); //buzz_2="Banana" 
      buzzArrayList.add(new Exchange(buzz_2)); 
      buzzAdapter.notifyDataSetChanged(); 
      } 
     }); 


     Call<Buzz> buzz3 = buzz_service.buzz_API("Rice"); 
     buzz3.enqueue(new Callback<Buzz>() { 
     @Override 
     public void onResponse(Call<Buzz> call, Response<Buzz> response) { 
      String buzz_3 = response.body().getBuzz(); //buzz_3="Rice" 
      buzzArrayList.add(new Exchange(buzz_3)); 
      buzzAdapter.notifyDataSetChanged(); 
      } 
     }); 
    } 

我只是想顯示的ListView以這樣的add()順序。

Apple 
Banana 
Rice 

但是,其實listview顯示是這樣的。

Banana 
Rice 
Apple 

Rice 
Banana 
Apple 

如何更改我的代碼顯示爲故意的嗎?我期待着您的回覆。謝謝。

+1

調用API同步 –

沙发
0
0

同步調用API。最好創建一個API.call同時該功能

Call<Buzz> buzz1 = buzz_service.buzz_API("Apple"); 
    buzz1.enqueue(new Callback<Buzz>() { 
    @Override 
    public void onResponse(Call<Buzz> call, Response<Buzz> response) { 
     String buzz_1 = response.body().getBuzz(); //buzz_1="Apple" 
     buzzArrayList.add(new Exchange(buzz_1)); 
     buzzAdapter.notifyDataSetChanged(); 

     Call<Buzz> buzz2 = buzz_service.buzz_API("Banana"); 
     buzz2.enqueue(new Callback<Buzz>() { 
     @Override 
     public void onResponse(Call<Buzz> call, Response<Buzz> response) { 
      String buzz_2 = response.body().getBuzz(); //buzz_2="Banana" 
      buzzArrayList.add(new Exchange(buzz_2)); 
      buzzAdapter.notifyDataSetChanged(); 

      Call<Buzz> buzz2 = buzz_service.buzz_API("Rice"); 
      buzz2.enqueue(new Callback<Buzz>() { 
      @Override 
      public void onResponse(Call<Buzz> call, Response<Buzz> response) { 
       String buzz_3 = response.body().getBuzz(); //buzz_3="Rice" 
       buzzArrayList.add(new Exchange(buzz_3)); 
       buzzAdapter.notifyDataSetChanged(); 
      }}); 
     }}); 
    }}); 
+0

謝謝您的回答!但這種方法不聰明...(如果我打電話給很多API) – NooNoo

+0

@NooNoo是的。它不聰明。異步調用速度更快。在一個ArrayList中添加一個id來區分項目。然後相應地排序! –

+0

添加您的響應結構我可以編輯答案 –

板凳
0
0

「蘋果」,「香蕉」,「大米」被添加到列表中的異步調用的函數,因此 中,他們被添加的順序是不可預測。 您以何種順序編寫異步調用enqueue並不重要。

要添加特定順序的項目, 最好將API_Interface和改造代碼更改爲使用同步方法而不是異步方式。這取決於你的改裝版本 語法是不同的, 按照文檔中的例子:

https://futurestud.io/tutorials/retrofit-synchronous-and-asynchronous-requests

不幸的是,文件指出, 在Android 4.0或更高版本的同步技術導致崩潰:

警告:同步請求觸發Android 4.0或更新版本的應用程序崩潰。你會遇到NetworkOnMainThreadException錯誤。

另一種選擇是通過其他方式序列化調用。 例如,您可以使用Semaphore s = new Semaphore(1), 在每個enqueue調用之前調用s.acquire(),並在每個onResponse調用中調用s.release()

即:

Semaphore s = new Semaphore(1); 

s.acquire(); 
Call<Buzz> buzz1 = buzz_service.buzz_API("Apple"); 
buzz1.enqueue(new Callback<Buzz>() { 
    @Override 
    public void onResponse(Call<Buzz> call, Response<Buzz> response) { 
     String buzz_1 = response.body().getBuzz(); //buzz_1="Apple" 
     buzzArrayList.add(new Exchange(buzz_1)); 
     buzzAdapter.notifyDataSetChanged(); 
     s.release(); 
    } 
}); 

s.acquire(); 
Call<Buzz> buzz2 = buzz_service.buzz_API("Banana"); 
buzz2.enqueue(new Callback<Buzz>() { 
    @Override 
    public void onResponse(Call<Buzz> call, Response<Buzz> response) { 
     String buzz_2 = response.body().getBuzz(); //buzz_2="Banana" 
     buzzArrayList.add(new Exchange(buzz_2)); 
     buzzAdapter.notifyDataSetChanged(); 
     s.release(); 
    } 
}); 

// ... 
+0

我正在使用Retrofit 2.如果我使用execute(),NetworkOnMainThreadExecption是導致....應該使用Asynctask? (對不起英語..) – NooNoo

0
votes
answers
28 views
+10

VB如何按升序和降序對ListView進行排序

0

我不明白爲什麼這不起作用。我有一個ListView,我希望能夠按升序和降序排序。當逐行逐行通過代碼時看起來一切順利,除了lvItems.Sorting將不等於Descending。它在None {0}和Ascending {1}之間處於一個常量循環中。VB如何按升序和降序對ListView進行排序

這裏是Form類:

Private Sub lvItems_ColumnClick(sender As Object, e As System.Windows.Forms.ColumnClickEventArgs) Handles lvItems.ColumnClick 

    ' If current column is not the previously clicked column 
    ' Add 
    If e.Column <> sortColumn Then 

     ' Set the sort column to the new column 
     sortColumn = e.Column 

     'Default to ascending sort order 
     lvItems.Sorting = SortOrder.Ascending 

    Else 

     'Flip the sort order 
     If lvItems.Sorting = SortOrder.Ascending Then 
      lvItems.Sorting = SortOrder.Descending 
     Else 
      lvItems.Sorting = SortOrder.Ascending 
     End If 
    End If 

    'Set the ListviewItemSorter property to a new ListviewItemComparer object 
    Me.lvItems.ListViewItemSorter = New ListViewItemComparer(e.Column, lvItems.Sorting) 

    ' Call the sort method to manually sort 
    lvItems.Sort() 

End Sub 

這裏是ListViewItemComparer類:

Public Class ListViewItemComparer 

    Implements IComparer 

    Private col As Integer 
    Private order As SortOrder 

    Public Sub New() 
     col = 0 
     order = SortOrder.Ascending 
    End Sub 

    Public Sub New(column As Integer, order As SortOrder) 
     col = column 
     Me.order = order 
    End Sub 

    Public Function Compare(x As Object, y As Object) As Integer Implements System.Collections.IComparer.Compare 

     Dim returnVal As Integer = -1 

     Try 

      ' Attempt to parse the two objects as DateTime 
      Dim firstDate As System.DateTime = DateTime.Parse(CType(x, ListViewItem).SubItems(col).Text) 
      Dim secondDate As System.DateTime = DateTime.Parse(CType(y, ListViewItem).SubItems(col).Text) 

      ' Compare as date 
      returnVal = DateTime.Compare(firstDate, secondDate) 

     Catch ex As Exception 

      ' If date parse failed then fall here to determine if objects are numeric 
      If IsNumeric(CType(x, ListViewItem).SubItems(col).Text) And 
       IsNumeric(CType(y, ListViewItem).SubItems(col).Text) Then 

       ' Compare as numeric 
       returnVal = Val(CType(x, ListViewItem).SubItems(col).Text).CompareTo(Val(CType(y, ListViewItem).SubItems(col).Text)) 

      Else 
       ' If not numeric then compare as string 
       returnVal = [String].Compare(CType(x, ListViewItem).SubItems(col).Text, CType(y, ListViewItem).SubItems(col).Text) 
      End If 

     End Try 

     ' If order is descending then invert value 
     If order = SortOrder.Descending Then 
      returnVal *= -1 
     End If 

     Return returnVal 

    End Function 

End Class 

不管是什麼數據我把我只能似乎得到升序排列。讓我知道是否有必要提供更多信息。

+1

不要設置'Sorting'和'ListViewItemSorter'。正如文檔所述,第一個用於按字母順序自動排序,第二個用於自定義排序。挑一個並使用它。 – jmcilhinney

沙发
0
0

感謝@ jmcilhinney的評論,我能夠解決問題。我沒有使用SortingListViewItemSorter,而是創建了一個字符串變量ordering併爲其分配了合適的排序順序(請參閱下面的最終解決方案)。

 'If current column is not the previously clicked column 
     'Add 
     If e.Column <> sortColumn Then 

      ' Set the sort column to the new column 
      sortColumn = e.Column 

      'Default to ascending sort order 
      ordering = "Ascending" 

     Else 

      'Flip the sort order 
      If ordering = "Ascending" Then 
       ordering = "Descending" 
      Else 
       ordering = "Ascending" 
      End If 
     End If 

     'Set the ListviewItemSorter property to a new ListviewItemComparer object 
     lvItems.ListViewItemSorter = New ListViewItemComparer(e.Column, ordering) 

     'Call the sort method to manually sort 
     lvItems.Sort() 
0
votes
answers
54 views
+10

ArrayList對象是Java的Android

2

我試圖從MySQL數據庫ArrayList對象,但結果添加對象上的ListView returing一行讓我只 我使用自定義適配器一行對我ListView,我想我可以使用環多對象ArrayList的對象,但我失敗了,請幫幫我,ArrayList對象是Java的Android

我的代碼:

String driver_fullname = json.getString("driver_fullname"); 
String driver_phonenumber = json.getString("driver_phonenumber"); 
String plate_no = json.getString("plate_no"); 
String parking_name = json.getString("parking_name"); 

List<PaymentTiming_Items> getAllDiverDetails = new ArrayList<PaymentTiming_Items>(); 
PaymentTiming_Items timingItems = new PaymentTiming_Items(); 
timingItems.setPlateNo(plate_no); 
timingItems.setParkingName(parking_name); 
timingItems.setDriverFullName(driver_fullname); 
getAllDiverDetails.add(timingItems); // store all drivers' info to 
} 

if (getAllDiverDetails.size() !=0) { 
userList = new ArrayList<> (getAllDiverDetails); 
listAdapter = new PaymentTiming_ListAdapter(getApplicationContext(), userList); 
myList.setAdapter(listAdapter); 
} 
+0

你可以添加自定義佈局xml ..檢查其高度是否「匹配prent」。如果它match_parent改爲wrap_content –

+0

@Tomin B自定義佈局是在自定義適配器,我認爲不是佈局 –

+0

添加如何加載多個數據。代碼中沒有循環。 –

沙发
0
2

看起來你正在創建一個ArrayList每次你解析的對象。如果我理解正確的話,你的代碼應該是類似的東西:

// ArrayList will be created only once for a json response. 
    List<PaymentTiming_Items> getAllDiverDetails = new ArrayList<PaymentTiming_Items>(); 

    //Now parse add all elements in json response and add to list. 
     for(all items in your jsonResponse List) {  
      //Parse fields from json object 
      String driver_fullname = json.getString("driver_fullname"); 
      String driver_phonenumber = json.getString("driver_phonenumber"); 
      String plate_no = json.getString("plate_no"); 
      String parking_name = json.getString("parking_name"); 

      //create object 
      PaymentTiming_Items timingItems = new PaymentTiming_Items(); 
      timingItems.setPlateNo(plate_no); 
      timingItems.setParkingName(parking_name); 
      timingItems.setDriverFullName(driver_fullname); 
      getAllDiverDetails.add(timingItems); // store all drivers' info to 
     } 

     //Now list will have all the items, Add this list to adapter. 
      if (getAllDiverDetails.size() !=0) { 
      userList = new ArrayList<>(getAllDiverDetails); 
      listAdapter = new PaymentTiming_ListAdapter(getApplicationContext(), userList); 
      myList.setAdapter(listAdapter); 
      } 
+0

謝謝,你說的對,我每次都在解析一個對象 –

板凳
0
1

假設您的服務器給出的結果,在JSONArray說作爲一個String 響應請嘗試以下

List<PaymentTiming_Items> getAllDiverDetails = new ArrayList<PaymentTiming_Items>(); 


     JSONArray jsonArray = new JSONArray(response); 
     int size = jsonArray.length(); 
     if (size > 0) 
     { 
      for (int i = 0; i < size; i++) 
      { 
       JSONObject jsonObject = jsonArray.getJSONObject(i); 
       String driver_fullname = json.getString("driver_fullname"); 
       String driver_phonenumber = json.getString("driver_phonenumber"); 
       String plate_no = json.getString("plate_no"); 
       String parking_name = json.getString("parking_name"); 


       PaymentTiming_Items timingItems = new PaymentTiming_Items(); 
       timingItems.setPlateNo(plate_no); 
       timingItems.setParkingName(parking_name); 
       timingItems.setDriverFullName(driver_fullname); 
       getAllDiverDetails.add(timingItems); // store all drivers' info to 
      } 
     } 

if (getAllDiverDetails.size() !=0) { 
userList = new ArrayList<> (getAllDiverDetails); 
listAdapter = new PaymentTiming_ListAdapter(getApplicationContext(), userList); 
myList.setAdapter(listAdapter); 
} 
地板
0
1

必須使用JSONArray爲從JSON獲取物品清單。然後用它們填充你的ArrayList並傳遞給你的適配器。

0
votes
answers
32 views
+10

從firebase檢索列表

-1

我知道如何獲取一個簡單的列表,但有問題時,如果節點嵌套像用戶輸入一個文本框,他想Section1的學生列表,然後只有傑裏和肖恩與他的輥沒有應該被顯示。 這是我的一個簡單列表的代碼。從firebase檢索列表

public class MainActivity extends AppCompatActivity { 
ListView listView; 
DatabaseReference dref; 
ArrayList<String> list=new ArrayList<>(); 
ArrayAdapter<String> adapter; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    listView=(ListView)findViewById(R.id.ListView); 
    adapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,list); 
    listView.setAdapter(adapter); 
    dref= FirebaseDatabase.getInstance().getReference(); 
    dref.addChildEventListener(new ChildEventListener() { 
     @Override 
     public void onChildAdded(DataSnapshot dataSnapshot, String s) { 
      String value=dataSnapshot.getValue(String.class); 
      list.add(value); 
      adapter.notifyDataSetChanged(); 
     } 

     @Override 
     public void onChildChanged(DataSnapshot dataSnapshot, String s) { 

     } 

     @Override 
     public void onChildRemoved(DataSnapshot dataSnapshot) { 
      String value=dataSnapshot.getValue(String.class); 
      list.remove(value); 
      adapter.notifyDataSetChanged(); 
     } 

     @Override 
     public void onChildMoved(DataSnapshot dataSnapshot, String s) { 

     } 

     @Override 
     public void onCancelled(DatabaseError databaseError) { 

     } 
    }); 
} 

JSON樹:

enter image description here

請建議我該怎麼做。

沙发
0
0

由於您將ChildEventListener附加到數據庫的根目錄,因此將爲每個部分調用onChildAdded的快照。所以一次爲Section1,一次爲Section2,一次爲Section3

如果你想只偵聽特定部分,你的聽衆連接至該節:

dref= FirebaseDatabase.getInstance().getReference(); 
dref.child("Section1").addChildEventListener(new ChildEventListener() { 
    @Override 
    public void onChildAdded(DataSnapshot dataSnapshot, String s) { 
     String key = dataSnapshot.getKey(); 
     int value = dataSnapshot.getValue(Integer.class); 
     list.add(key+": "+value); 
     adapter.notifyDataSetChanged(); 
    } 

在上面的,因爲你只是聽Section1,你onChildAdded將觸發一次Jerry和一次用於Sean。但這些快照現在是,所以代碼使用getKey()

另一方面:如果您想要顯示所有部分的學生,您需要將您的偵聽器保留在根目錄並訪問原始快照的較低級屬性。爲此,您需要使用getChild()才能到達酒店,或者使用getChildren()來訪問所有酒店。

dref= FirebaseDatabase.getInstance().getReference(); 
dref.addChildEventListener(new ChildEventListener() { 
    @Override 
    public void onChildAdded(DataSnapshot dataSnapshot, String s) { 
     for (DataSnapshot student: dataSnapshot.getChildren()) { 
      String value=student.getValue(String.class); 
      list.add(value); 
     } 
     adapter.notifyDataSetChanged(); 
    } 
+0

請問有什麼辦法同時顯示名稱和值像我的列表中它只是顯示滾動no.And非常感謝你爲解決 – fuk

+0

我更新了第一個片段使用'信息getKey()'和' getValue(Integer.class)'來獲取名稱和值。 –

0
votes
answers
34 views
+10

將一些文本插入到視圖中

0

我不熟悉Android編程。我只是想知道如何將文本插入Android中的視圖?或者如果它不可能,我該如何在視圖中插入一個字符串?我試圖做的是在視圖中放置佈局和文本。將一些文本插入到視圖中

final LayoutInflater layoutInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

TextView tx = new TextView(this); 
View vw; 
Boolean hasRow = false; 
ListView lv = findViewById(R.id.lv); 

tx.setText("asdasd"); 

if(hasRow){ 
    vw = layoutInflater.inflate(R.layout.row, null); 
} else { 
    vw = layoutInflater.inflate(R.layout.row2, null); 
} 

lv.addFooterView(vw, tx.getText(), true); 
lv.setAdapter(adapter); 

我的代碼讓我插入一個佈局但沒有文字的視圖。請幫忙。謝謝!

沙发
0
0

如果您想將文字設置爲TextView作爲ListView的頁腳。使用TextView從一個相關的佈局(行或行2)。

if (hasRow){ 
    vw = layoutInflater.inflate(R.layout.row, null); 
} else { 
    vw = layoutInflater.inflate(R.layout.row2, null); 
} 

TextView footTextView = vw.findViewById(R.id.txt_your_footer); 
footTextView.setText("asdasd"); 
lv.addFooterView(vw); 
+0

你是什麼意思txt_your_footer?它只是一個textview? – bonsoy

+0

它是行或第2行xml中TextView的標識。我認爲你需要爲腳註添加TextView - kimkevin剛纔 – kimkevin

+0

哦,那樣做!謝謝kimkevin! – bonsoy

0
votes
answers
38 views
+10

xamarin形式的網格人口

0

首先我剛剛開始使用xamarin形式,並且c#我設法使用了listviews,但是當涉及到網格時我有點兒困惑,基本上我需要的是將一個對象綁定到那這樣的表現網格意甲:每行xamarin形式的網格人口

2列,我設法與此代碼做到這一點:

<Grid HorizontalOptions="Fill" VerticalOptions="Fill" Margin="10"> 
      <Grid.RowDefinitions> 
       <RowDefinition Height="1*" /> 
       <RowDefinition Height="1*" /> 
       <RowDefinition Height="1*" /> 
      </Grid.RowDefinitions> 
      <Grid.ColumnDefinitions> 
       <ColumnDefinition Width="1*" /> 
       <ColumnDefinition Width="1*" /> 
      </Grid.ColumnDefinitions> 

      <!--fila 1--> 
      <StackLayout Grid.Column="0" Grid.Row="0" BackgroundColor="Blue" HorizontalOptions="Fill"></StackLayout> 
      <StackLayout Grid.Column="1" Grid.Row="0" BackgroundColor="Red" HorizontalOptions="Fill"></StackLayout> 
      <!--fila 2--> 
      <StackLayout Grid.Column="0" Grid.Row="1" BackgroundColor="Red" HorizontalOptions="Fill"></StackLayout> 
      <StackLayout Grid.Column="1" Grid.Row="1" BackgroundColor="Blue" HorizontalOptions="Fill"></StackLayout> 
      <!--fila 3--> 
      <StackLayout Grid.Column="0" Grid.Row="2" BackgroundColor="Blue" HorizontalOptions="Fill"></StackLayout> 
       <StackLayout Grid.Column="1" Grid.Row="2" BackgroundColor="Red" 
    HorizontalOptions="Fill"></StackLayout> 
    </Grid> 

enter image description here

但是,我不知道如何與填充網格信息動態。與listview是相當簡單的,因爲它只有綁定命令,在這裏我沒有想法,有人可以請我指出正確的方向? 謝謝。

+0

網格是一個佈局容器,它不支持數據綁定。您可以使用Grid's Children集合在運行時將控件添加到網格中。 – Jason

+0

@Jason謝謝,我想知道至少我如何使用它,我認爲這將使用foreach的,但我不知道! –

沙发
0
0
int row = 0; 
int col = 0; 

// data is a List<string> 
foreach (var text in data) { 
    var label = new Label() { Text = text }; 
    grid.Children.Add(box, col, row); 

    col++; 
    if (col > 1) { 
    col = 0; 
    row++; 
    } 

} 
0
votes
answers
14 views
+10

GridView控件 - 圖像,文本和項目單擊

-2

我的朋友 我是一個新的Android和我想做一個例子(代碼)喜歡的圖片 GridView控件 - 圖像,文本和項目單擊 感謝所有enter image description hereGridView控件 - 圖像,文本和項目單擊

+1

你應該開始尋找在線教程...問題太廣泛,因爲SO – Selvin

+1

去Fiverr並付錢給你,讓它爲你 – Forbs

+0

不要去fiverr,讓別人爲你做,他們會做它以最簡單快捷的方式,而不會考慮未來的問題。 –

沙发
0
0

你正在尋找RecyclerView。創建佈局並添加recyclerView它然後創建了recyclerview下面的行另一個佈局文件:

<RelativeLayout 
       android:id="@+id/relativeLayout2" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent"> 

       <android.support.v7.widget.RecyclerView 
        android:id="@+id/recyclerView" 
        android:layout_width="match_parent" 
        android:layout_height="match_parent"/> 

</RelativeLayout> 

創建另一個佈局row_layout.xml

<RelativeLayout 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"> 


    <ImageView 
     android:id="@+id/imageView" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     app:srcCompat="@mipmap/ic_launcher" /> 

    <TextView 
     android:id="@+id/textView" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="TextView"/> 

</RelativeLayout> 

然後在你的MainActivity,加上下面幾行代碼:

RecyclerView recyclerView = findViewById(R.id.recyclerView); 
recyclerView.setHasFixedSize(true); 
RecyclerView.LayoutManager gridLayoutManager = new GridLayoutManager(this, 2, false); 
recyclerView.setLayoutManager(gridLayoutManager); 

在此之後,根據您的具體需要進行recyclerView可以用快速谷歌搜索發現創建一個適配器。只需在適配器的onCreateViewHolder中重新啓動row_layout即可。創建適配器後,只需將其設置爲您的recyclerView。

recyclerView.setAdapter(your_custom_adapter); 

這只是你應該做的事情的要點。它會讓你開始正確的方向。其餘的只是一個搜索。