0

다른 ListView와 옵션으로 간단한 탭 응용 프로그램을 만들려고합니다. 탭과 MainActivity 사이의 관계를 관리하고 싶습니다. 현재 탭 단추의 addItem() 함수를 사용하여 탭 응용 프로그램의 ListView (조각 내부)에 새 항목을 추가 할 수 없습니다. 이미 많은 것을 검색했고, 단순한 ListView (MainActivity 내부)에 항목을 추가하거나 탭 응용 프로그램에 동적으로 항목을 추가하지 않는 것에 대해서만 발견했습니다.안드로이드 - 조각 목록 (탭)에 새 항목 추가 - 안드로이드 스튜디오

그래서 여기는 내 탭 응용 프로그램과 ListView의 화면입니다. 내가) (메뉴 버튼 방식 action_add을 구현하기 위해 노력하고 있음을, MainActivity.java

public class MainActivity extends AppCompatActivity { 



private SectionsPagerAdapter mSectionsPagerAdapter; 

/** 
* The {@link ViewPager} that will host the section contents. 
*/ 
private ViewPager mViewPager; 

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 
    // Create the adapter that will return a fragment for each of the three 
    // primary sections of the activity. 
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); 

    // Set up the ViewPager with the sections adapter. 
    mViewPager = (ViewPager) findViewById(R.id.container); 
    mViewPager.setAdapter(mSectionsPagerAdapter); 

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); 
    tabLayout.setupWithViewPager(mViewPager); 

} 

CustomList을 가진 조각 : 여기

[1]: https://i.stack.imgur.com/Ze4eu.png

그리고 Custom List View Application Picture

내 코드입니다

public class Catalogo extends Fragment { 
    ArrayList<CustomList> custom = null; 
    ListView lv = null; 
    ArrayAdapter adapter = null; 
    ArrayList<CustomList> elementos = new ArrayList<CustomList>(); 

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.catalogo, container, false); 
     ListView lv = rootView.findViewById(R.id.catalogoListView); 

     custom = addItems(); 
     adapter = new CustomAdapter(this.getContext(), custom); 
     lv.setAdapter(adapter); 

     return rootView; 
    } 

    private ArrayList<CustomList> addItems(){ 
     CustomList custom = new CustomList("Banana", "4.0"); 
     elementos.add(custom); 
     custom = new CustomList("Morango", "5.0"); 
     elementos.add(custom); 
     return elementos; 
    } 

    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 


     if (id == R.id.action_add){ 
      AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity()); 
      //builder.setTitle("Adicionar novo item"); //THESE ARE NOT WORKING 
      //final EditText input = new EditText(this); //THIS SHOULD BE 2 Text Fields 
      //builder.setView(input); 
      builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        //NEED TO IMPLEMENT HERE 
       } 
      }); 
      builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        dialog.cancel(); 
       } 
      }); 
      builder.show(); 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 
    public static String preferredCase(String original, String price) 
    { 
     if (original.isEmpty()) 
      return original; 

     return original.substring(0, 1).toUpperCase() + original.substring(1).toLowerCase(); 
    } 

} 

내 CustomItem 구조 :

public class CustomList { 
    String name; 
    String price; 
    public CustomList(String name, String price) { 
     this.name = name; 
     this.price = price; 
    } 
    public String getName() { 
     return name; 
    } 
    public String getPrice() { 
     return price; 
    } 
} 

그리고 마지막에, 내 CustomAdapter이 :

public class CustomAdapter extends ArrayAdapter<CustomList> { 
    private final Context context; 
    private final ArrayList<CustomList> elementos; 

    public CustomAdapter(Context context, ArrayList<CustomList> elementos){ 
     super(context, R.layout.modelolista, elementos); 
     this.context = context; 
     this.elementos = elementos; 
    } 
    public View getView(int position, View convertView, ViewGroup parent){ 
     LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View rowView = inflater.inflate(R.layout.modelolista, parent, false); 

     TextView nameItem = rowView.findViewById(R.id.tvName); 
     TextView priceItem = rowView.findViewById(R.id.tvPrice); 

     nameItem.setText(elementos.get(position).getName()); 
     priceItem.setText(elementos.get(position).getPrice()); 

     return rowView; 
    } 
} 
+0

죄송 합니다만, 나는 그것을 얻지 못했습니다. 메뉴 항목을 클릭하고 추가 목록을 알려서 업데이트 된 목록을 표시 할 수 있도록 목록에 항목을 추가 하시겠습니까? –

+0

네가 맞아요, 메뉴 항목으로 목록에 항목을 추가하십시오. 문제는 .. MainActivity에서 목록 및 메뉴 항목을 구현하지만 조각에서 구현할 수 없습니다. 두 가지 옵션이 있습니다. 먼저 MainActivity에서 CustomList와 모든 메뉴 버튼을 구현하지만,이 "만든 사용자 정의 목록"을 조각 ("카탈로그"탭)에 전달하는 방법을 모르겠습니다. 둘째, Fragment ("Catalogo"탭) 내부의 모든 것을 구현하지만, MainActivity에서와 같은 버튼 기능을 구현할 수 없습니다. –

+0

괜찮 았어. 카탈로그 조각이 표시되거나 항상 볼 때만 "추가"단추가 표시됩니다. –

답변

0

조각의 활동의 데이터를 사용하는 가장 좋은 방법은 조각에서 인터페이스를 만들고 활동 클래스에 구현하는 것입니다

public class Catalogo extends Fragment { 
    private CatalogFragmentInteface catalogInterface; 
    //rest of your code 

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
      View rootView = inflater.inflate(R.layout.catalogo, container, false); 
      catalogIntreface.catalogInterfaceFunction(rootView); 
    } 
@Override 
    public void onAttach(Context context) { 
     super.onAttach(context); 
     if (context instanceof CatalogFragmentInterface) { 
      catalogInterface = (CatalogFragmentInterface) context; 
     } else { 
      throw new RuntimeException(context.toString() 
        + " must implement CatalogFragmentInterface"); 
     } 
    } 

    interface CatalogFragmentInterface { 
     void catalogInterfaceFunction(View view); 
    } 
    } 

그리고 Activity 클래스에서이 인터페이스를 구현하십시오.

public class MainActivity extends AppCompatActivity implement Catalog.CatalogFragmentInterface{ 
@Overide 
void catalogInterfaceFunction(View view) { 
    //access your listview in fragment using view variable 
} 
} 

이렇게하면 모든 데이터와 목록보기가 같은 클래스에 존재합니다. 이것이 도움이되기를 바랍니다. 모든 제안의

+0

나는 나의 대답을 편집했다 –

+0

미안 나는 그것을 알아 차리지 않았다, 나는이 대답을 여기에 썼다. 변수 이름을 바꿀 수 있습니다 –

+0

그래, 내 코드를 섞을 때 엉망이 됐어. 불편을 드려 죄송합니다. –

0

첫째 : 대신 CustomListItem 호출을 고려, 당신의 품목 CustomList 호출. 이 방법을 사용하면 앞으로 목록에서 항목이 아니라 쉽게 기억할 수 있습니다.

그렇다면 페이지 추가 대화 상자를 구현해야합니다.

이 있습니다 .. "최선의 방법"을 (내가 생각하는) 사용자 정의 대화 상자를 추가 생성됩니다 수행하기위한 여러 가지 방법이 있습니다. 이제

AlertDialog.Builder builder = new AlertDialog.Builder(activity); 
LayoutInflater inflater = activity.getLayoutInflater(); 
View dialogView = inflater.inflate(R.layout.my_custom_view, null); 
builder.setView(dialogView); 

당신은 단순히 모든 listners를 구현하고 들어 Button byButton = (Button)dialogView.getItemById(R.id.mybutton);

으로 얻는 아이템으로 여기에 거즈 수 : 그래서 당신은 사용자 정의 레이아웃을 생성하고이 같은 뭔가 레이아웃의보기로 제공해야합니다 도움이 될만한 정보 확인 this answer (많은 정보가 있습니다).

당신은 당신의 Activity에 사용자 정의 Fragment의 참조를 저장할 수 있습니다

이제 우리는 목록보기를 상쾌 그리워 무엇을, 내 생각이 가장 간단한 방법입니다. 그런 다음 AddItemToList()처럼 Fragment 방법에 추가 할 수 있습니다.

콜백 (MainActivity)

//add this param 
private MyFragment myFragment; 

//when you show the fragment add this: 
myFragment = myFragmentIstance; 

//on the save of the dialog, add this: 
//do all checks and create item 
CustomListItem cli = new CustomListItem(editTextName.getText().toString(), editTextPrice.getText().toString()); 
myFragment.AddItemToList(cli); 

AddItemToList (- 유저가 "추가"를 클릭 이제 때 버튼을, 당신은 당신의 조각 참조에서이 메소드를 호출 할 수 있으며, 아래와 같은 방법을 구현 (+) 조각) :이 같은

public void AddItemToList(CustomListItem cli){ 
    myCustomListItemList.Add(cli); 
    myAdapterView.notifyDataSetChanged(); 
} 

뭔가 내가 여기 어떤 질문이나 explaination를 들어 .. 작동합니다. 행운을 빌어 요.

+0

Fragment에서 콜백이 onAttach가 아니어야합니다 ? –