2012-01-30 2 views
1

안녕하세요.이 사진을 보셔서 감사합니다. 안드로이드 개발자 가이드를 사용하여 동적 ListView를 만들었습니다. 현재 ListView 액티비티는 XML 파일이나 setContentView ...에 대한 필요없이 화면에 표시되는 것처럼 보입니다. 이는 문제입니다.동적 ListView를 만들었습니다 - XML ​​레이아웃 파일에 어떻게 연결합니까?

XML 레이아웃을 사용하여 목록을 표시하는 데 전체 활동을 할당하는 대신 다른보기를 화면에 추가 할 수 있습니다. 빈 ListView가 포함 된 XML 레이아웃을 만들었습니다. 목록을 할당 된 공간으로 가져 오길 원합니다. 그렇다면 제 질문 : ListActivity에서 레이아웃 XML 파일을 사용하려면 어떻게해야합니까?

public class MainList extends ListActivity { 
    static SharedPreferences statusSettings; 
    String jsonString; 
    static JSONObject json; 
    static JSONArray arrayTest; 
    static int bob = 3; 



    @Override 
    protected void onListItemClick(ListView l, View v, int position, long id) { 
     // TODO Auto-generated method stub 
     super.onListItemClick(l, v, position, id); 

     try { 
      JSONObject e = arrayTest.getJSONObject(position); 
      Intent intent = new Intent(); 
      intent.putExtra("clientName", e.getString("proj_name")); 
      intent.putExtra("clientAddress", e.getString("c_address")); 
      intent.putExtra("clientComments", e.getString("comments")); 
      intent.putExtra("clientOrder", e.getString("order")); 
      intent.setClass(MainList.this, ClientDetails.class); 
      MainList.this.startActivity(intent); 


     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      Log.e("JSON", "Problem creating object from array!"); 
      e.printStackTrace(); 
     } 
    } 

    private static class EfficientAdapter extends BaseAdapter { 
     private LayoutInflater mInflater; 


     public EfficientAdapter(Context context) { 
      // Cache the LayoutInflate to avoid asking for a new one each time. 
      mInflater = LayoutInflater.from(context); 

     } 

     public int getCount() { 
      return arrayTest.length(); 

     } 

     public Object getItem(int position) { 
      return position; 
     } 

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

     public View getView(int position, View convertView, ViewGroup parent) { 

      ViewHolder holder; 

      if (convertView == null) { 
       convertView = mInflater.inflate(R.layout.mainlist, null); 

       holder = new ViewHolder(); 
       holder.textName = (TextView) convertView.findViewById(R.id.tvMainName); 
       holder.textAddress = (TextView) convertView.findViewById(R.id.tvMainAddress); 


       convertView.setTag(holder); 
      } else { 

       holder = (ViewHolder) convertView.getTag(); 
      } 


      JSONObject e; 
      try { 
       e = arrayTest.getJSONObject(position); 
       holder.textName.setText(e.getString("proj_name")); 
       holder.textAddress.setText(e.getString("c_address")); 


       switch (statusSettings.getInt(e.getString("order"), 0)){ 
        case 1: 
         convertView.setBackgroundColor(0x00000000); 
         break; 
        case 2: 
         if(bob == 3){ 
          convertView.setBackgroundColor(0xFFFF6600); 
          bob = 5; 
         } 
         break; 
        case 3: 
         convertView.setBackgroundColor(0xFF00CC00); 
         break; 
        case 4: 
         convertView.setBackgroundColor(0xFFCC0000); 
         break; 
       } 



      } catch (JSONException e1) { 
       // TODO Auto-generated catch block 
       Log.e("JSON", "Couldn't put one of JSON arrays into object"); 
       e1.printStackTrace(); 
      } 



      return convertView; 
     } 

     static class ViewHolder { 
      TextView textName; 
      TextView textAddress; 
     } 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     jsonString = getIntent().getExtras().getString("jsonString"); 
     try { 
      json = new JSONObject(jsonString); 
      arrayTest = json.getJSONArray("client_list"); 
     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      Log.e("JSON", "Couldn't create the JSON Array"); 
      e.printStackTrace(); 
     } 
     setListAdapter(new EfficientAdapter(this)); 

    } 

    @Override 
    protected void onResume() { 
     // TODO Auto-generated method stub 
     super.onResume(); 
     bob = 3; 

     statusSettings = getSharedPreferences("status", 0); 



     setListAdapter(new EfficientAdapter(this)); 
    } 


} 

XML 파일 : - 나는 완전히 이해가 안 돼요,하지만 나는 그것이 LayoutInflater에서 함께 할 수있는 뭔가가 가정

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 

    <ListView 
     android:id="@+id/list" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" android:layout_weight="1"> 
    </ListView> 


    <Button 
     android:id="@+id/button1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Button" /> 

</LinearLayout> 

것은이다, 그들은 어떤 XML 레이아웃을 사용하지 않고 그것을 만들 수 있습니다. 나는 시도했다 : convertView = mInflater.inflate (R.id.list, null);

대신

대신 convertView = mInflater.inflate (R.layout.mainlist, null);

및 setContentView (R.layout.test); 내 onCreate에 ...하지만 작동하지 않았다. 당신이 제공하는 도움이 많이 감사 할 것입니다, 감사합니다!

+0

은 올바르게 작성된 R 파일입니까? – shiraz

+0

그래, 문제가 보이지 않고 프로그램이 np를 컴파일한다. – Wildblood

+0

Btw 여기에 안드로이드 dev을 배울 수있는 훌륭한 리소스입니다 http : //www.youtube.com/playlist? list = PLE953C0B85B50AB62 & feature = plcp 초기 비디오 몇 장을 훑어보고 도움이되는지 확인합니다. – shiraz

답변

0

이것은 매우 간단합니다. 참조 용으로 몇 가지 코드를 빠르게 생성했습니다.

public class ListandtextActivity extends Activity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     final String [] str = {"ONE","TWO","THREE"}; 
     final ListView lv = (ListView) findViewById(R.id.listView1); 
     final TextView tv = (TextView)findViewById(R.id.tv1); 
     lv.setAdapter(new ArrayAdapter<Object>(getApplicationContext(), android.R.layout.simple_list_item_1, str)); 
     lv.setOnItemClickListener(new OnItemClickListener(){ 
      @Override 
      public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { 
       tv.setText("You Clicked Something"); 
      } 
     }); 
    } 
} 

그리고 당신의 XML

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 

    <TextView 
     android:id="@+id/tv1" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="@string/hello" /> 

    <ListView 
     android:id="@+id/listView1" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" > 
    </ListView> 

</LinearLayout> 

당신이 의심이 있다면 물어 주시기 바랍니다에

.

+0

시도해 보았습니다. lv.setAdapter (new ArrayAdapter (getApplicationContext(), android.R.layout.simple_list_item_1, str)); BaseAdapter를 확장하는 효율적인 어댑터가 있습니다. 불행히도 작동하지 않습니다. ( – Wildblood

+0

어댑터에 문제가있을 수 있습니다. 내 컴퓨터에서이 코드를 실행했습니다. 오류가 발생하면 logcat을 붙여 넣을 수 있습니까? –

+0

01-30 13 : 25 : 17.103 : E/AndroidRuntime (25869) : 치명적인 예외 : 주 01-30 13 : 25 : 17.103 : E/AndroidRuntime (25869) : java.lang.NullPointerException 01-30 13 : 25 : 17.103 : E /AndroidRuntime (25869) : \t at hal.makios.v3.MainList2 $ EfficientAdapter.getView (MainList2.java:151) – Wildblood

관련 문제