kandi background
Explore Kits

baseAdapter | Android 万能的Adapter | RecyclerView library

 by   hongyangAndroid Java Version: Current License: Apache-2.0

 by   hongyangAndroid Java Version: Current License: Apache-2.0

Download this library from

kandi X-RAY | baseAdapter Summary

baseAdapter is a Java library typically used in User Interface, RecyclerView applications. baseAdapter has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has medium support. You can download it from GitHub.
Android 万能的Adapter for ListView,RecyclerView,GridView等,支持多种Item类型的情况。
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • baseAdapter has a medium active ecosystem.
  • It has 4619 star(s) with 1195 fork(s). There are 163 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 107 open issues and 17 have been closed. On average issues are closed in 224 days. There are 6 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of baseAdapter is current.
baseAdapter Support
Best in #RecyclerView
Average in #RecyclerView
baseAdapter Support
Best in #RecyclerView
Average in #RecyclerView

quality kandi Quality

  • baseAdapter has 0 bugs and 0 code smells.
baseAdapter Quality
Best in #RecyclerView
Average in #RecyclerView
baseAdapter Quality
Best in #RecyclerView
Average in #RecyclerView

securitySecurity

  • baseAdapter has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • baseAdapter code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
baseAdapter Security
Best in #RecyclerView
Average in #RecyclerView
baseAdapter Security
Best in #RecyclerView
Average in #RecyclerView

license License

  • baseAdapter is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
baseAdapter License
Best in #RecyclerView
Average in #RecyclerView
baseAdapter License
Best in #RecyclerView
Average in #RecyclerView

buildReuse

  • baseAdapter releases are not available. You will need to build from source code and install.
  • Build file is available. You can build the component from source.
  • Installation instructions are not available. Examples and code snippets are available.
  • baseAdapter saves you 1021 person hours of effort in developing the same functionality from scratch.
  • It has 2318 lines of code, 204 functions and 53 files.
  • It has medium code complexity. Code complexity directly impacts maintainability of the code.
baseAdapter Reuse
Best in #RecyclerView
Average in #RecyclerView
baseAdapter Reuse
Best in #RecyclerView
Average in #RecyclerView
Top functions reviewed by kandi - BETA

kandi has reviewed baseAdapter and discovered the below as its top functions. This is intended to give you an instant insight into baseAdapter implemented functionality, and help decide if they suit your requirements.

  • Initializes the RecyclerView .
  • Invoked when an item is selected .
  • Set the listener for the view
  • Callback when the inner view is attached to the inner view .
  • Creates and returns a ViewHolder instance based on a layoutId .
  • Draws a vertical view vertically .
  • Returns an ItemViewDelegate for a specific position
  • Returns a string representation of this ChatMessage .
  • Checks to see if the item is for a specific view type
  • Determine if the position is in the footer position .

baseAdapter Key Features

Android 万能的Adapter for ListView,RecyclerView,GridView等,支持多种Item类型的情况。

ForRecyclerView

copy iconCopydownload iconDownload
compile 'com.zhy:base-rvadapter:3.0.3'

ForListView

copy iconCopydownload iconDownload
compile 'com.zhy:base-adapter:3.0.3'

使用

copy iconCopydownload iconDownload
mRecyclerView.setAdapter(new CommonAdapter<String>(this, R.layout.item_list, mDatas)
{
    @Override
    public void convert(ViewHolder holder, String s)
    {
        holder.setText(R.id.id_item_list_title, s);
    }
});

onViewHolderCreated

copy iconCopydownload iconDownload
mListView.setAdapter(new CommonAdapter<String>(this, R.layout.item_list, mDatas)
{
    @Override
    public void convert(ViewHolder holder, String o, int pos)
    {
        holder.setText(R.id.id_item_list_title, o);
    }

    @Override
    public void onViewHolderCreated(ViewHolder holder, View itemView)
    {
        super.onViewHolderCreated(holder, itemView);
       //AutoUtil.autoSize(itemView)
    }
});

java.lang.ClassCastException: android.text.SpannableStringBuilder cannot be cast to com.ree.kms.DakaHinbanClass

copy iconCopydownload iconDownload
  @Override
    public void afterTextChanged(Editable s){

        DakaHinbanClass temp = valueList.get(mPosition);
        temp.Query = s.toString();
    }

How to implement a listview with an adapter in a fragment in Android Studio

copy iconCopydownload iconDownload
    public class HomeFragment extends Fragment {
    
        String mTitle[] = {"1987", "Congorama", "Bon cop bad cop 2"};
        String mDescription[] = {"Lieu: Québec", "Lieu: Saint-Michel", "Lieu: Montréal"};
        int images[] = {R.drawable.mille, R.drawable.congorama, R.drawable.bcb2};
    
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
    
            View view = inflater.inflate(R.layout.fragment_home, container, false);
    

...

            ListView listView = (ListView) view.findViewById(R.id.Listview); //use listview from inflater view instead of getActivity
          
...

  MyAdapter myadapter = new MyAdapter( getContext(), mTitle, mDescription, images);
            listView.setAdapter(myadapter);
    
            // Inflate the layout for this fragment
            return view;
        }
    
    }
-----------------------
String mTitle[] = {"1987", "Congorama", "Bon cop bad cop 2"};
String mDescription[] = {"Lieu: Québec", "Lieu: Saint-Michel", "Lieu: Montréal"};
int images[] = {R.drawable.mille, R.drawable.congorama, R.drawable.bcb2};


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

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

    ListView listView = (ListView) getActivity().findViewById(R.id.Listview);
    MyAdapter myadapter = new MyAdapter( getContext(), mTitle, mDescription, images);
    listView.setAdapter(myadapter);

    // Inflate the layout for this fragment
    return view;
}

Custom Listview setonItemClickListner is not working in DialogFragment using Viewbinding in kotlin

copy iconCopydownload iconDownload
override fun getItem(p0: Int): Serve = servNo[p0]

Android Studio - how to update Fragment's UI onButtonClick in a listview using BaseAdapter

copy iconCopydownload iconDownload
public interface Callback {
    public void OnFavoriteClicked()
}
Adapter adapter = new Adapter(this@Fragment)
adapter.setCallback(this)
callback.OnFavoriteClicked()
class Adapter() ... {
    
 interface Callback {
       fun action()
    }
    
    private var callback: Callback? = null

    fun setListener(callback: Callback) {
       this.callback = callback
    }
    
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
       holder.itemView.setOnClickListener {
         callback?.action()
       }
    }

...

class ExampleFragment : Fragment, Adapter.Callback {

    ...

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val adapter = Adapter()
        adapter.setListener(this)
    }

    override fun action() {
        //Callback from adapter
    }

}
-----------------------
public interface Callback {
    public void OnFavoriteClicked()
}
Adapter adapter = new Adapter(this@Fragment)
adapter.setCallback(this)
callback.OnFavoriteClicked()
class Adapter() ... {
    
 interface Callback {
       fun action()
    }
    
    private var callback: Callback? = null

    fun setListener(callback: Callback) {
       this.callback = callback
    }
    
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
       holder.itemView.setOnClickListener {
         callback?.action()
       }
    }

...

class ExampleFragment : Fragment, Adapter.Callback {

    ...

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val adapter = Adapter()
        adapter.setListener(this)
    }

    override fun action() {
        //Callback from adapter
    }

}
-----------------------
public interface Callback {
    public void OnFavoriteClicked()
}
Adapter adapter = new Adapter(this@Fragment)
adapter.setCallback(this)
callback.OnFavoriteClicked()
class Adapter() ... {
    
 interface Callback {
       fun action()
    }
    
    private var callback: Callback? = null

    fun setListener(callback: Callback) {
       this.callback = callback
    }
    
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
       holder.itemView.setOnClickListener {
         callback?.action()
       }
    }

...

class ExampleFragment : Fragment, Adapter.Callback {

    ...

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val adapter = Adapter()
        adapter.setListener(this)
    }

    override fun action() {
        //Callback from adapter
    }

}
-----------------------
public interface Callback {
    public void OnFavoriteClicked()
}
Adapter adapter = new Adapter(this@Fragment)
adapter.setCallback(this)
callback.OnFavoriteClicked()
class Adapter() ... {
    
 interface Callback {
       fun action()
    }
    
    private var callback: Callback? = null

    fun setListener(callback: Callback) {
       this.callback = callback
    }
    
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
       holder.itemView.setOnClickListener {
         callback?.action()
       }
    }

...

class ExampleFragment : Fragment, Adapter.Callback {

    ...

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val adapter = Adapter()
        adapter.setListener(this)
    }

    override fun action() {
        //Callback from adapter
    }

}
-----------------------
public interface Callback {
    public void OnFavoriteClicked()
}
Adapter adapter = new Adapter(this@Fragment)
adapter.setCallback(this)
callback.OnFavoriteClicked()
class Adapter() ... {
    
 interface Callback {
       fun action()
    }
    
    private var callback: Callback? = null

    fun setListener(callback: Callback) {
       this.callback = callback
    }
    
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
       holder.itemView.setOnClickListener {
         callback?.action()
       }
    }

...

class ExampleFragment : Fragment, Adapter.Callback {

    ...

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val adapter = Adapter()
        adapter.setListener(this)
    }

    override fun action() {
        //Callback from adapter
    }

}
-----------------------
btn_like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // stuff you want
            }
        });
Integer.valueOf(tv_like.getText().toString())+1;
tv_like.setText((Integer.valueOf(tv_like.getText().toString())+1) + "");
btn_like.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            tv_like.setText((Integer.valueOf(tv_like.getText().toString())+1) + "");
        }
    });
-----------------------
btn_like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // stuff you want
            }
        });
Integer.valueOf(tv_like.getText().toString())+1;
tv_like.setText((Integer.valueOf(tv_like.getText().toString())+1) + "");
btn_like.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            tv_like.setText((Integer.valueOf(tv_like.getText().toString())+1) + "");
        }
    });
-----------------------
btn_like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // stuff you want
            }
        });
Integer.valueOf(tv_like.getText().toString())+1;
tv_like.setText((Integer.valueOf(tv_like.getText().toString())+1) + "");
btn_like.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            tv_like.setText((Integer.valueOf(tv_like.getText().toString())+1) + "");
        }
    });
-----------------------
btn_like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // stuff you want
            }
        });
Integer.valueOf(tv_like.getText().toString())+1;
tv_like.setText((Integer.valueOf(tv_like.getText().toString())+1) + "");
btn_like.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            tv_like.setText((Integer.valueOf(tv_like.getText().toString())+1) + "");
        }
    });

Android- Check multiple items and delete from list of RecyclerView

copy iconCopydownload iconDownload
fun removeAllCheckedItems() {
    dataList.filter { it.isSelected }
        .forEach { removeItems(it) }
}
setOnCheckedChangeListener { buttonView, isChecked ->
    model.isChecked = isChecked
}
-----------------------
fun removeAllCheckedItems() {
    dataList.filter { it.isSelected }
        .forEach { removeItems(it) }
}
setOnCheckedChangeListener { buttonView, isChecked ->
    model.isChecked = isChecked
}

when apply something in position it will apply also on other position in custom ListView

copy iconCopydownload iconDownload
public class Listview1Adapter extends BaseAdapter {
    final ArrayList<ItemState> data;

    public Listview1Adapter(ArrayList<ItemState> arr) {
        data = arr;
    }

    private static class ItemState {
        final HashMap<String, Object> data;
        boolean isExpanded;

        public ItemState(final HashMap<String, Object> data, final boolean isExpanded) {
            this.data = data;
            this.isExpanded = isExpanded;
        }
    }

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

    @Override
    public HashMap<String, Object> getItem(int index) {
        return data.get(index).data;
    }

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

    @Override
    public View getView(final int _position, View _v, ViewGroup _container) {
        LayoutInflater _inflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = _v;
        if (v == null) {
            v = _inflater.inflate(R.layout.online_block_list, null);
        }


        final ImageView drop_more = v.findViewById(R.id.drop_more);
        final LinearLayout linearMore = v.findViewById(R.id.linearMore);
        final LinearLayout linearDro = v.findViewById(R.id.linearDro);


        if (data.get(_position).isExpanded) { // check current view state for item
            linearMore.setVisibility(View.VISIBLE); // restore view state for current item
        } else {
            linearMore.setVisibility(View.GONE); // restore view state for current item
        }


        linearDro.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (linearMore.getVisibility() == View.GONE) {

                    final android.transition.ChangeBounds transition = new android.transition.ChangeBounds();
                    transition.setDuration(200L);
                    android.transition.TransitionManager.beginDelayedTransition(listview1, transition);
                    linearMore.setVisibility(View.VISIBLE);
                    data.get(_position).isExpanded = true;  // save view state for item

                    ObjectAnimator.ofFloat(drop_more, View.ROTATION, 0f, 180f).setDuration(300).start();

                } else {
                    final android.transition.ChangeBounds transition = new android.transition.ChangeBounds();
                    transition.setDuration(200L);
                    android.transition.TransitionManager.beginDelayedTransition(listview1, transition);
                    linearMore.setVisibility(View.GONE);
                    data.get(_position).isExpanded = false;  // save view state for item

                    ObjectAnimator.ofFloat(drop_more, View.ROTATION, 180f, 0f).setDuration(300).start();

                }
            }
        });
        return v;
    }
}
final ArrayList<HashMap<String, Object>> listMapTest = new ArrayList<>(); // input data

// 1th
final ArrayList<ItemState> viewListMapTest_1 = listMapTest.stream().map(item -> new ItemState(item, false)).collect(Collectors.toCollection(ArrayList::new));
        
// 2th:
final ArrayList<ItemState> viewListMapTest_2 = new ArrayList<ItemState>() {{
      for (HashMap<String, Object> item : listMapTest) add(new ItemState(item, false));
        }};
        
// 3th:
final ArrayList<ItemState> viewListMapTest_3 = new ArrayList<>(listMapTest.size());
    for (int i = 0; i < viewListMapTest_3.size(); i++) {
        viewListMapTest_3.set(i, new ItemState(listMapTest.get(i), false));
    }

-----------------------
public class Listview1Adapter extends BaseAdapter {
    final ArrayList<ItemState> data;

    public Listview1Adapter(ArrayList<ItemState> arr) {
        data = arr;
    }

    private static class ItemState {
        final HashMap<String, Object> data;
        boolean isExpanded;

        public ItemState(final HashMap<String, Object> data, final boolean isExpanded) {
            this.data = data;
            this.isExpanded = isExpanded;
        }
    }

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

    @Override
    public HashMap<String, Object> getItem(int index) {
        return data.get(index).data;
    }

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

    @Override
    public View getView(final int _position, View _v, ViewGroup _container) {
        LayoutInflater _inflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = _v;
        if (v == null) {
            v = _inflater.inflate(R.layout.online_block_list, null);
        }


        final ImageView drop_more = v.findViewById(R.id.drop_more);
        final LinearLayout linearMore = v.findViewById(R.id.linearMore);
        final LinearLayout linearDro = v.findViewById(R.id.linearDro);


        if (data.get(_position).isExpanded) { // check current view state for item
            linearMore.setVisibility(View.VISIBLE); // restore view state for current item
        } else {
            linearMore.setVisibility(View.GONE); // restore view state for current item
        }


        linearDro.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (linearMore.getVisibility() == View.GONE) {

                    final android.transition.ChangeBounds transition = new android.transition.ChangeBounds();
                    transition.setDuration(200L);
                    android.transition.TransitionManager.beginDelayedTransition(listview1, transition);
                    linearMore.setVisibility(View.VISIBLE);
                    data.get(_position).isExpanded = true;  // save view state for item

                    ObjectAnimator.ofFloat(drop_more, View.ROTATION, 0f, 180f).setDuration(300).start();

                } else {
                    final android.transition.ChangeBounds transition = new android.transition.ChangeBounds();
                    transition.setDuration(200L);
                    android.transition.TransitionManager.beginDelayedTransition(listview1, transition);
                    linearMore.setVisibility(View.GONE);
                    data.get(_position).isExpanded = false;  // save view state for item

                    ObjectAnimator.ofFloat(drop_more, View.ROTATION, 180f, 0f).setDuration(300).start();

                }
            }
        });
        return v;
    }
}
final ArrayList<HashMap<String, Object>> listMapTest = new ArrayList<>(); // input data

// 1th
final ArrayList<ItemState> viewListMapTest_1 = listMapTest.stream().map(item -> new ItemState(item, false)).collect(Collectors.toCollection(ArrayList::new));
        
// 2th:
final ArrayList<ItemState> viewListMapTest_2 = new ArrayList<ItemState>() {{
      for (HashMap<String, Object> item : listMapTest) add(new ItemState(item, false));
        }};
        
// 3th:
final ArrayList<ItemState> viewListMapTest_3 = new ArrayList<>(listMapTest.size());
    for (int i = 0; i < viewListMapTest_3.size(); i++) {
        viewListMapTest_3.set(i, new ItemState(listMapTest.get(i), false));
    }

Fragment does not show up

copy iconCopydownload iconDownload
BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {

        NavController controller = Navigation.findNavController(MainActivity.this, R.id.nav_host_fragment);  // R.id.nav_host_fragment is the id of the placeholder fragment in content_main.xml
        controller.navigate(R.id.nav_newview);           
    }
};
navController.navigate(R.id.secondFragment, null, getNavOptions());

NavOptions getNavOptions() {
    return new NavOptions.Builder()
            .setEnterAnim(R.anim.fragment_open_enter)
            .setExitAnim(R.anim.nav_default_exit_anim)
            .setPopEnterAnim(R.anim.nav_default_pop_enter_anim)
            .setPopExitAnim(R.anim.nav_default_pop_exit_anim)
            .build();
}
-----------------------
BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {

        NavController controller = Navigation.findNavController(MainActivity.this, R.id.nav_host_fragment);  // R.id.nav_host_fragment is the id of the placeholder fragment in content_main.xml
        controller.navigate(R.id.nav_newview);           
    }
};
navController.navigate(R.id.secondFragment, null, getNavOptions());

NavOptions getNavOptions() {
    return new NavOptions.Builder()
            .setEnterAnim(R.anim.fragment_open_enter)
            .setExitAnim(R.anim.nav_default_exit_anim)
            .setPopEnterAnim(R.anim.nav_default_pop_enter_anim)
            .setPopExitAnim(R.anim.nav_default_pop_exit_anim)
            .build();
}

Unable to send fragments back in Java

copy iconCopydownload iconDownload
        manager = getSupportFragmentManager();
        Fragment fr = FilesFragment.newInstance(files);
        transaction = manager.beginTransaction();
        transaction.addToBackStack("initialFragment"); // also may be null
        transaction.add(R.id.fragment_container, fr);
        transaction.commit();
-----------------------
@Override
public void onBackPressed(){
    FragmentManager fm = getFragmentManager();
    if (fm.getBackStackEntryCount() > 0) {
        Log.i("MainActivity", "popping backstack");
        fm.popBackStack();
    } else {
        Log.i("MainActivity", "nothing on backstack, calling super");
        super.onBackPressed();  
    }
}
public void onBackPressed()
{
    FragmentManager fm = getActivity().getSupportFragmentManager();
    fm.popBackStack();
}
-----------------------
@Override
public void onBackPressed(){
    FragmentManager fm = getFragmentManager();
    if (fm.getBackStackEntryCount() > 0) {
        Log.i("MainActivity", "popping backstack");
        fm.popBackStack();
    } else {
        Log.i("MainActivity", "nothing on backstack, calling super");
        super.onBackPressed();  
    }
}
public void onBackPressed()
{
    FragmentManager fm = getActivity().getSupportFragmentManager();
    fm.popBackStack();
}
-----------------------
@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
          int count = getSupportFragmentManager().getBackStackEntryCount();
            if(count==1){
                finish();
            }
        }
        return super.onKeyDown(keyCode,event);
    }
-----------------------
private static File[] files;

public FilesFragment(File[] files) {
  this.files = files;     
}

Save locale language after restart the app using shared prefrences

copy iconCopydownload iconDownload
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Locale locale = new Locale("tr"); // get this value from shared pref
        Locale.setDefault(locale);
        Resources resources = activity.getResources();
        Configuration config = resources.getConfiguration();
        config.setLocale(locale);
        resources.updateConfiguration(config, resources.getDisplayMetrics());

        setContentView(R.layout.activity_ui_settings);

        currentLanguage = getIntent().getStringExtra(currentLang);
        spinner = (Spinner) findViewById(R.id.spinner);

        final List<String> list = new ArrayList<String>();
        list.add(getString(R.string.selectlang));
        list.add("Türkçe");
        list.add("English");
        list.add("Pусский");
        final CustomAdapter adapter = new CustomAdapter(getApplicationContext(),flags, (ArrayList<String>) list);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                switch (position) {

                    case 1:
                        setLocale("tr");
                        break;
                    case 2:
                        setLocale("en");
                        break;
                    case 3:
                        setLocale("ru");
                        break;

                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

ListView, how to centered elements

copy iconCopydownload iconDownload
ListView android:layout_width="wrap_content"
android:layout_width="match_parent"
-----------------------
ListView android:layout_width="wrap_content"
android:layout_width="match_parent"

Community Discussions

Trending Discussions on baseAdapter
  • java.lang.ClassCastException: android.text.SpannableStringBuilder cannot be cast to com.ree.kms.DakaHinbanClass
  • How to implement a listview with an adapter in a fragment in Android Studio
  • Custom Listview setonItemClickListner is not working in DialogFragment using Viewbinding in kotlin
  • Android Studio - how to update Fragment's UI onButtonClick in a listview using BaseAdapter
  • AdapterViewFlipper stops flipping after two clicks
  • Kotlin Gridview display issue on click and Scroll
  • Android- Check multiple items and delete from list of RecyclerView
  • Huawei Push Exception: com.huawei.hms.common.ApiException: 907122037: get token error
  • Custom adapter in coroutine
  • when apply something in position it will apply also on other position in custom ListView
Trending Discussions on baseAdapter

QUESTION

java.lang.ClassCastException: android.text.SpannableStringBuilder cannot be cast to com.ree.kms.DakaHinbanClass

Asked 2022-Apr-01 at 05:56

I want to add EditText to the listview, but I can't do it smoothly. Please guide. If it is List<String>, it is normal, but DakaHinbanClass is used, How to write code that uses Class

The data is obtained from MySQL, and the content can be displayed normally at present. I want to change the production quantity directly in the listview, but when running, the position of line 195 always reports an error.

ErrorCode:

2022-03-31 15:58:14.780 13403-13403/com.ree.kms E/AndroidRuntime: FATAL EXCEPTION: main Process: com.ree.kms, PID: 13403 java.lang.ClassCastException: android.text.SpannableStringBuilder cannot be cast to com.ree.kms.DakaHinbanClass at com.ree.kms.DakaListAdapterClass$MyTextWatcher.afterTextChanged(DakaListAdapterClass.java:195) at android.widget.TextView.sendAfterTextChanged(TextView.java:8336) at android.widget.TextView.setText(TextView.java:4399) at android.widget.TextView.setText(TextView.java:4247) at android.widget.EditText.setText(EditText.java:90) at android.widget.TextView.setText(TextView.java:4222) at com.ree.kms.DakaListAdapterClass.getView(DakaListAdapterClass.java:101) at android.widget.AbsListView.obtainView(AbsListView.java:2474) at android.widget.ListView.makeAndAddView(ListView.java:1920) at android.widget.ListView.fillDown(ListView.java:717) at android.widget.ListView.fillFromTop(ListView.java:778) at android.widget.ListView.layoutChildren(ListView.java:1701) at android.widget.AbsListView.onLayout(AbsListView.java:2235) at android.view.View.layout(View.java:16953) at android.view.ViewGroup.layout(ViewGroup.java:5579) at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1189) at android.view.View.layout(View.java:16953) at android.view.ViewGroup.layout(ViewGroup.java:5579) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:396) at android.widget.FrameLayout.onLayout(FrameLayout.java:333) at android.view.View.layout(View.java:16953) at android.view.ViewGroup.layout(ViewGroup.java:5579) at android.widget.LinearLayout.setChildFrame(LinearLayout.java:2001) at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1844) at android.widget.LinearLayout.onLayout(LinearLayout.java:1753) at android.view.View.layout(View.java:16953) at android.view.ViewGroup.layout(ViewGroup.java:5579) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:396) at android.widget.FrameLayout.onLayout(FrameLayout.java:333) at android.view.View.layout(View.java:16953) at android.view.ViewGroup.layout(ViewGroup.java:5579) at android.widget.LinearLayout.setChildFrame(LinearLayout.java:2001) at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1844) at android.widget.LinearLayout.onLayout(LinearLayout.java:1753) at android.view.View.layout(View.java:16953) at android.view.ViewGroup.layout(ViewGroup.java:5579) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:396) at android.widget.FrameLayout.onLayout(FrameLayout.java:333) at com.android.internal.policy.PhoneWindow$DecorView.onLayout(PhoneWindow.java:2740) at android.view.View.layout(View.java:16953) at android.view.ViewGroup.layout(ViewGroup.java:5579) at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2562) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2265) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1323) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6718) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:894) at android.view.Choreographer.doCallbacks(Choreographer.java:696) at android.view.Choreographer.doFrame(Choreographer.java:631) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:880) at android.os.Handler.handleCallback(Handler.java:815) at android.os.Handler.dispatchMessage(Handler.java:104) at android.os.Looper.loop(Looper.java:207) at android.app.ActivityThread.main(ActivityThread.java:5765) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)

DakaListAdapterClass

package com.ree.kms;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;

import java.util.List;

public class DakaListAdapterClass extends BaseAdapter {

    String contains1,contains2;
    Context context;
    List<DakaHinbanClass> valueList;
    private int mTouchItemPosition=-1;

    public DakaListAdapterClass(List<DakaHinbanClass> listValue,Context context){
        this.context = context;
        this.valueList = listValue;
    }

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

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

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

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

        ViewItem_Daka viewItem_daka = null;
        if (convertView == null){
            viewItem_daka = new ViewItem_Daka();
            LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(R.layout.listview_daka,null);
            viewItem_daka.TextViewHinban = convertView.findViewById(R.id.tv_daka_hinban);
            viewItem_daka.TextViewQuery = convertView.findViewById(R.id.tv_daka_query);
            viewItem_daka.TextViewKyakusaki = convertView.findViewById(R.id.tv_daka_kyakusaki);
            viewItem_daka.TextViewDate_End = convertView.findViewById(R.id.tv_daka_date_end);
            viewItem_daka.TextViewRemarks = convertView.findViewById(R.id.tv_daka_remarks);
            viewItem_daka.TextViewCyui = convertView.findViewById(R.id.tv_daka_cyui);
            viewItem_daka.TextViewRakasu = convertView.findViewById(R.id.tv_daka_rakasu);
            viewItem_daka.EditTextQuery_out = convertView.findViewById(R.id.tv_daka_query_out);

            viewItem_daka.EditTextQuery_out.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    mTouchItemPosition = (int) v.getTag();

                    if ((v.getId()==R.id.tv_daka_query_out && canVertivalScroll((EditText) v) )){
                        v.getParent().requestDisallowInterceptTouchEvent(true);
                        if (event.getAction()== MotionEvent.ACTION_UP){
                            v.getParent().requestDisallowInterceptTouchEvent(false);
                        }
                    }
                    return false;
                }
            });

            viewItem_daka.mTextWatcher = new MyTextWatcher();
            viewItem_daka.EditTextQuery_out.addTextChangedListener(viewItem_daka.mTextWatcher);
            viewItem_daka.updatePosition(position);

            convertView.setTag(viewItem_daka);
        }else{
            viewItem_daka = (ViewItem_Daka) convertView.getTag();
            viewItem_daka.updatePosition(position);
        }

        viewItem_daka.TextViewHinban.setText("品番:"+valueList.get(position).Hinban);
        viewItem_daka.TextViewQuery.setText("着荷数:"+valueList.get(position).Query);
        viewItem_daka.TextViewKyakusaki.setText("取引先:"+valueList.get(position).Kyakusaki);
        viewItem_daka.TextViewDate_End.setText("完成予定:"+valueList.get(position).Date_end);
        viewItem_daka.TextViewRakasu.setText("落下数:"+valueList.get(position).Rakasu);

        viewItem_daka.EditTextQuery_out.setText(valueList.get(position).Query);
        viewItem_daka.TextViewRemarks.setText("備考:"+valueList.get(position).Remarks);
        viewItem_daka.TextViewStatus = valueList.get(position).Status;

        if (mTouchItemPosition==position){
            viewItem_daka.EditTextQuery_out.requestFocus();
            viewItem_daka.EditTextQuery_out.setSelection(viewItem_daka.EditTextQuery_out.getText().length());
        }else{
            viewItem_daka.EditTextQuery_out.clearFocus();
        }

        if (TextUtils.isEmpty(valueList.get(position).Cyui)){
            viewItem_daka.TextViewCyui.setText("注意:なし");
        }else {
            viewItem_daka.TextViewCyui.setText("注意:" + valueList.get(position).Cyui);
        }

        contains1= (String) viewItem_daka.TextViewCyui.getText();
        contains2= (String) viewItem_daka.TextViewStatus;
        if(contains1.equals("注意:なし")){
            viewItem_daka.TextViewCyui.setTextColor(Color.parseColor("#808080"));

        }else{
            viewItem_daka.TextViewCyui.setTextColor(Color.parseColor("#FF0000"));
        }

        if (!contains2.contains("生産済")){
            convertView.setBackgroundResource(R.drawable.listview_daka_background);
        }else{
            convertView.setBackgroundResource(R.drawable.listview_chaka_background);
        }
        return convertView;
    }

    private boolean canVertivalScroll(EditText editText){
        int scrollY = editText.getScrollY();
        int scrollRange = editText.getLayout().getHeight();
        int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() - editText.getCompoundPaddingBottom();
        int scrollDifference = scrollRange - scrollExtent;
        if (scrollDifference == 0){
            return false;
        }
        return (scrollY>0) || (scrollY < scrollDifference -1 );
    }
    class ViewItem_Daka {
        TextView TextViewHinban;
        TextView TextViewQuery;
        TextView TextViewDate_End;
        TextView TextViewKyakusaki;
        TextView TextViewCyui;
        TextView TextViewRemarks;
        TextView TextViewFusoku;
        TextView TextViewRakasu;
        EditText EditTextQuery_out;
        TextView TextViewQuery_out;
        String TextViewStatus;
        MyTextWatcher mTextWatcher;
        public void updatePosition(int position){
            mTextWatcher.updatePosition(position);
        }
    }

    class MyTextWatcher implements TextWatcher{
        private int mPosition;
        public void updatePosition(int Position){
            mPosition = Position;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            valueList.set(mPosition, (DakaHinbanClass) s);    ←error is here
        }
    }
}

DakaHinbanClass

package com.ree.kms;

public class DakaHinbanClass {
    public String HinbanId;
    public String Hinban;
    public String HangaNumber;
    public String Date_end;
    public String Query;
    public String Weight;
    public String WeightAll;
    public String Cyui;
    public String Query_out;
    public String Remarks;
    public String Kyakusaki;
    public String Status;
    public String Fusoku,Rakasu,FuryoHakuri,FuryoHaiki;
}

@Override public void afterTextChanged(Editable s) { valueList.set(mPosition, s.toString()); ←That's not right }

ANSWER

Answered 2022-Apr-01 at 05:56

After the user changes the string inside the EditText, the method afterTextChanged(Editable s) is called, and s represents the new edited String. You want to update the DakaHinbanClass object inside the list, so you can't just conver a String an object (this String is only one class member of this object class, right?)

If you want to update the Query value inside this object, first get the object and then set the class member value to the new String, like this:

  @Override
    public void afterTextChanged(Editable s){

        DakaHinbanClass temp = valueList.get(mPosition);
        temp.Query = s.toString();
    }

Source https://stackoverflow.com/questions/71688466

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install baseAdapter

You can download it from GitHub.
You can use baseAdapter like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the baseAdapter component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.