2013-07-11 5 views
1

여러분이 도와 드리겠습니다.다중 목록보기 항목 클릭 한 클래스로 클릭

저는 10 개의 이미지 버튼 클릭 및 목록보기 인 텐트를 모두 처리하는 활동이 있습니다. 내가 뭘 하려는지 모든 목록보기 버튼 클릭에 대한 1 레이아웃이 있습니다. 그리고이 레이아웃에서는 다른 데이터를 호출합니다. 내가이 프로젝트를 시작했을 때 많은 스택 오버플로 사용자가 내가 그것을 더 간단하게 만들 수 있고 많은 것을 명확하게 할 수있을 때까지 나는 많은 활동을했다.

누군가 내 코드에서 모든 목록보기의 모든 항목 클릭을 호출 할 수있는 수업을 만드는 방법을 보여줄 수 있다면 좋을 것입니다.

package com.example.testtest; 

import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.ArrayAdapter; 
import android.widget.ImageButton; 
import android.widget.ListView; 

public class MainActivity extends Activity implements OnClickListener{ 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.layout_of_button); 
ImageButton btn1 = (ImageButton)findViewById(R.id.imageButton1); 
ImageButton btn2 = (ImageButton)findViewById(R.id.imageButton2); 
ImageButton btn3 = (ImageButton)findViewById(R.id.imageButton3); 
ImageButton btn4 = (ImageButton)findViewById(R.id.imageButton4); 
ImageButton btn5 = (ImageButton)findViewById(R.id.imageButton5); 
ImageButton btn6 = (ImageButton)findViewById(R.id.imageButton6); 
btn1.setOnClickListener(this); 
btn2.setOnClickListener(this); 
btn3.setOnClickListener(this); 
btn4.setOnClickListener(this); 
btn5.setOnClickListener(this); 
btn6.setOnClickListener(this); 
} 

@Override 
public void onClick(View v) { 
    switch(v.getId()) { 
    // if one of the image buttons is pressed... 
    case R.id.imageButton1: 
    case R.id.imageButton2: 
    case R.id.imageButton3: 
    case R.id.imageButton4: 
    case R.id.imageButton5: 
    case R.id.imageButton6: 
     Intent intent = new Intent(this, Listviewact.class); 
     // pass ID of pressed button to listview-activity 
     intent.putExtra("buttonId", v.getId()); 
     startActivity(intent); 
     break; 
    // here you could place handling of other clicks if necessary...   
    } 
} 

private void setListAdapter(ArrayAdapter<String> arrayAdapter) { 
// TODO Auto-generated method stub 

} 

private ListView getListView() { 
// TODO Auto-generated method stub 
    return null; 
} 
} 

청어.

http://img40.imageshack.us/img40/705/f6h9.png

+0

나는 당신이 원하는 것을 정확히 혼동합니다.목록에서 항목을 클릭하고 싶다면 무엇을 클릭 했습니까? 클릭 한 모든 항목이있는 새로운 '활동'을 열 수있는 버튼을 클릭하십시오. – codeMagic

+0

안녕하세요 마술은 내가 어떤 목록보기 항목 (모두)을 클릭 할 때마다 다른 정보로 재사용 할 수있는 새로운 레이아웃을 열어 모든 항목 clicks.or에 대해 하나의 수업을 더 어렵게 만드는 경우입니다. 내 스스로 알려주세요. – coolcat

+0

당신은 분명히 할 수 있습니다 ... 나는 항상 그렇게합니다. 당신이 무엇을 클릭하든 동일한 '레이아웃'을 기대하는 한, 약간 다를 수 있지만 여전히 관리가 가능합니다. '정적 ArrayList' 또는 비슷한 것을 저장하는 클래스를 만들거나'Intent.extras'를 통해 데이터를 전송할 수 있습니다 – codeMagic

답변

0

내가 원하는 것을 이해하면 항목을 클릭 할 때마다 static Arraylist과 같은 것을 추가하여 클래스를 추가 할 수 있습니다. 그럼 당신은 당신이 여기에서 필요로하는 어떤 다른 getters/setters 또는 추가 할 수 있습니다

public class Data class 
{ 
    static ArrayList<String> dataArray = new ArrayList<String>();; 

    public Data() 
    { 
     // empty constructor but could be used if needed 
    } 

같은 수준의 뭔가를 만들 수 있습니다. 당신이 항목을 클릭하면 당신은 다음 다음 Activity 여기에서 항목을 검색

Data.dataArray.add("stuff"); 

뭔가를 호출합니다. 즉 너무 복잡 이상이면

은 다음 필요한 것보다 당신은 당신이 또한 Intent

Intents

을 통해 필요 ArrayList 또는 어떤 물체 단지 선호도를 통과 할 수 있지만, 당신의 Button의 모든 이후 똑같은 일을하면, 그것들을 초기화하고 모두에 listeners을 설정하는 것으로 처리 할 수 ​​있습니다. XML로 바로 거기 case 문이 필요 그들은 모두 같은 일을하기 때문에도없고 당신이 implements OnClickListener 필요하지 않습니다 각 Button

`android:onClick="someFunctionName"` 

는 그 함수 이름

public void someFunctionName(View v) { 
switch(v.getId()) { 
// if one of the image buttons is pressed... 

    Intent intent = new Intent(this, Listviewact.class); 
    // pass ID of pressed button to listview-activity 
    intent.putExtra("buttonId", v.getId()); 
    startActivity(intent); 
    break; 
// here you could place handling of other clicks if necessary...   
} 

을 사용하여 추가 Activity 선언

+0

코드를 사용하여 약간 바보 같은 느낌을주었습니다. 코딩에 익숙하지 않은만큼, 나는 진드기를 내 머리 위로 치고 싶다. 그게 내가 나중에 explane하는 하드. – coolcat

+0

이 마술은 내가하고 싶은 부분이다. http://img594.imageshack.us/img594/9373/a7l8.png 이제 처음 두 이미지가 완성되었지만,이 마지막 클래스/이미지는 코드 작성이 어렵다. . 마지막 수업은 두 번째 image.That에 목록보기에서 제목에 대한 다른 텍스트/데이터/정보를 가지고 있기 때문에 나는 50 데이터를 가지고 싶지 않기 때문에이 질문을 물어 자신의 데이터/정보. 나는 많이 느낀다. 1 클래스를 가지고 그냥보기를 변경하거나 다른 데이터를 textview에 삽입하는 방법이 될 수 있습니다. 시작하기 위해 나에게 줄 수있는 코드는 내가 이해할 필요가있는 것일 수 있습니다. – coolcat

+0

좋아, 나는 당신이 원하는 것을 이해한다고 생각합니다. 첫 번째 예제와 같은 클래스를 사용하면 효과가 있습니다. 항목을 클릭하면 관련 데이터가 해당 클래스에 저장됩니다. 당신이 무엇을 필요로하는지 모르겠으므로 그것을 설정하는 방법을 말하기가 어렵습니다. 당신은 다른'String', int's,'ArrayList','HashMap'을 가질 수 있습니다 ... 그것은 당신의 상황에 맞는 것에 달려 있습니다. 이것은 데이터를 프리젠 테이션 레벨과 분리하여 유지하는 좋은 방법입니다. – codeMagic

0

당신은 ListView를 사용하지만, 어떤 콜백있어 사용하지? 여기, 내 코드는 내 ListView에 사용됩니다. 내 배열에 활동을 넣고 있지만, 무엇이든 넣을 수 있습니다. R.layout.mfd_view을 수정하면 각 목록 항목에 대해 원하는 것을 넣을 수 있습니다. A Button 그것이 필요한 경우. 희망이 도움이됩니다. 나는 아직도 나 자신을 배우고있다.

import android.app.Activity; 
import android.app.ListFragment; 
import android.content.Context; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ArrayAdapter; 
import android.widget.ListAdapter; 
import android.widget.ListView; 

public class MyListFragment extends ListFragment { 
String fragmentBackStack; 
MyMapHandler handler; 
OnViewSelectedListener mListener; 

/** 
* An array of POJOs used to hold the info about the fragments we'll be 
* swapping between This should be inserted into an array adapter of some 
* sort before being passed onto ListAdapter 
*/ 
private static final ViewDetails[] ACTIVITY_DETAILS = { 
     new ViewDetails(R.string.action_largeTach, 
       R.string.largeTach_description, LargeTachActivity.class), 
     new ViewDetails(R.string.action_map, R.string.map_description, 
       MyMapHandler.class), 
     new ViewDetails(R.string.action_navigation, 
       R.string.navigation_description, NavigationActivity.class), 
     new ViewDetails(R.string.action_raceMode, 
       R.string.raceMode_description, RaceModeActivity.class), 
     new ViewDetails(R.string.action_settings, 
       R.string.settings_description, SettingsFragment.class), 
     new ViewDetails(R.string.action_extraInfo, 
       R.string.extraInfo_description, ExtraInfoActivity.class) }; 

/** 
* @author PyleC1 
* 
*   A POJO that holds a class object and it's resource info 
*/ 
public static class ViewDetails { 
    private final Class<? extends Activity> viewActivity; 
    private int titleId; 
    private int descriptionId; 

    /** 
    * @param titleId 
    *   The resource ID of the string for the title 
    * @param descriptionId 
    *   The resource ID of the string for the description 
    * @param activityClass 
    *   The fragment's class associated with this list position 
    */ 
    ViewDetails(int titleId, int descriptionId, 
      Class<? extends Activity> viewActivity) { 

     super(); 
     this.titleId = titleId; 
     this.descriptionId = descriptionId; 
     this.viewActivity = viewActivity; 
    } 

    public Class<? extends Activity> getViewActivity() { 
     return viewActivity; 
    } 
} 

/** 
* @author PyleC1 
* 
*   Extends the ArrayAdapter class to support our custom array that 
*   we'll insert into the ListAdapter so the user can pick between 
*   MFD screens at boot time. 
*/ 
private static class CustomArrayAdapter extends ArrayAdapter<ViewDetails> { 
    public CustomArrayAdapter(Context context, ViewDetails[] activities) { 
     super(context, R.layout.mfd_view, R.id.mfdTitle, activities); 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     MFDView mfdView; 

     if (convertView instanceof MFDView) { 
      mfdView = (MFDView) convertView; 
     } else { 
      mfdView = new MFDView(getContext()); 
     } 

     ViewDetails details = getItem(position); 

     mfdView.setTitleId(details.titleId); 
     mfdView.setDescriptionId(details.descriptionId); 

     return mfdView; 
    } 
} 

public void onAttach(Activity activity) { 
    super.onAttach(activity); 

    ListAdapter listAdapter = new CustomArrayAdapter(getActivity(), 
      ACTIVITY_DETAILS); 
    setListAdapter(listAdapter); 

    try { 
     mListener = (OnViewSelectedListener) activity; 
    } catch (ClassCastException e) { 
     throw new ClassCastException(activity.toString() 
       + " must implement OnViewSelectedListener!"); 
    } 
} 

@Override 
public void onResume() { 
    super.onResume(); 
} 

public interface OnViewSelectedListener { 
    public void onViewSelected(Class<? extends Activity> activityClass); 
} 

public void onListItemClick(ListView l, View v, int position, long id) { 
    ViewDetails details = (ViewDetails) getListAdapter().getItem(position); 

    mListener.onViewSelected(details.viewActivity); 
} 
} 

이 조각을 호출하는 모든 작업에는 OnViewSelectedListener 인터페이스를 구현해야합니다. 주 활동에 하위 클래스로 추가 한 경우이 작업은 필요하지 않습니다. public void onListItemClick(arg0, arg1, arg2, arg3) 콜백이 좋습니다. 조각을 교환하거나 내부에서 활동을 호출하기 만하면됩니다.

+0

현재 모든 imagebutton 중 하나를 클릭하면 잘된다. 활동이 잘 열리고 listview가 거기에서 작동하며 여기에서 새로운 활동/레이아웃을 열고 싶다. clciked.if가 누락 된 모든 목록보기 항목에서 나에게 환락을 알리십시오. 범위를 좁히십시오 ... 우리는 결국 거기에 도달 할 것입니다.) – coolcat

+0

그래서 사용자가 선택한 것으로부터 새로운 동적 레이아웃을 만들려고합니까? 아마도 번들을 묶어 새로운 활동으로 보내야 할 것입니다. 그런 다음 새 액티비티의 레이아웃에서 0dp로 뷰 컨테이너를 설정하고 다양한 'android : layout_weight'값을 설정합니다. 그러면 새로운 활동에서'onCreate (Bundle)'에서 프래그먼트를 표시하거나 숨길 수 있습니다. 'FragmentManager'를 호출하기 전에'setContentView (int)'를 호출해야합니다. – DownrangeFuture

관련 문제