I create a custom DialogFragment. It contains a listView, but when the list calls setAdapter there is a NullPointerException. I can't understand why.
This is the code:
public class LineUpConfirm extends DialogFragment {
private ListView list;
private List<ItemLineUpConfirm> pList = new ArrayList<ItemLineUpConfirm>();
private AdapterListConfirmLineUp adapter;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.confirm_lineup_layout, null));
pList.add(new ItemLineUpConfirm("P", "C. Abbiati","MIL","INT"));
pList.add(new ItemLineUpConfirm("D", "C. Papastapopulos","SAS","VER"));
pList.add(new ItemLineUpConfirm("C", "Cacca","SAM","GEN"));
adapter = new AdapterListConfirmLineUp(CurrentContext.getContext(),
R.layout.item_confirm_lineup, pList);
list = (ListView) getActivity().findViewById(R.id.list_confirm_lineup);
list.setAdapter(adapter); // HERE NullPointerException
return builder.create();
}
}
This is the layout of my Dialogfragment:
<?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" >
<TextView
android:id="#+id/title_progressdialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Formazione creata"
android:layout_margin="5dp" />
<ListView
android:id="#+id/list_confirm_lineup"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#fff"
android:divider="#575555"
android:dividerHeight="1dp" />
<Button
android:id="#+id/button_confirm_lineup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Conferma"
android:layout_gravity="center" />
</LinearLayout>
Your list is null because you're trying to get the View from the Activity layout instead of the one of the Dialog.
Try to keep a reference of the Dialog view and get it from there:
View dialogView = inflater.inflate(R.layout.confirm_lineup_layout, null);
// some code
list = (ListView) dialogView.findViewById(R.id.list_confirm_lineup);
I update your method
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.confirm_lineup_layout, null);
builder.setView(v);
pList.add(new ItemLineUpConfirm("P", "C. Abbiati", "MIL", "INT"));
pList.add(new ItemLineUpConfirm("D", "C. Papastapopulos", "SAS", "VER"));
pList.add(new ItemLineUpConfirm("C", "Cacca", "SAM", "GEN"));
adapter = new AdapterListConfirmLineUp(CurrentContext.getContext(), R.layout.item_confirm_lineup, pList);
list = (ListView) v.findViewById(R.id.list_confirm_lineup);
list.setAdapter(adapter); // HERE NullPointerException
return builder.create();
}
The problem was you are trying to find the listview from activity but it is actually in alertbuilder view. So I just change that.
Related
First, I created activity with RecyclerView, it works fine. My original code:
activity_agreements.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/list"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:paddingTop="8dp"
android:scrollbars="vertical"
app:layout_constraintBottom_toTopOf="#+id/editText"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<TextView
android:id="#+id/editText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:ems="10"
android:gravity="left"
android:inputType="none|text|textPersonName"
android:text="* required fields"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/btnGetSelected"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
<Button
android:id="#+id/btnGetSelected"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_marginBottom="4dp"
android:text="I agree"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
</android.support.constraint.ConstraintLayout>
Agreements list passed to ActivityAgreements and adapter setup:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_agreements);
btnGetSelected = findViewById(R.id.btnGetSelected);
list = findViewById(R.id.list);
list.setLayoutManager(new LinearLayoutManager(this));
list.setHasFixedSize(true);
agreements = getIntent().getParcelableArrayListExtra("agreements");
AgreementsAdapter adapter = new AgreementsAdapter(this.agreements);
list.setAdapter(adapter);
My adapter code:
public class AgreementsAdapter extends RecyclerView.Adapter<AgreementsAdapter.ViewHolder>
{
ArrayList<Agreement> agreements;
public AgreementsAdapter(List<Agreement> agreements)
{
this.agreements = new ArrayList<>(agreements);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.agreement_list_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position)
{
holder.bindData(agreements.get(position));
holder.checkbox.setOnCheckedChangeListener(null);
holder.checkbox.setChecked(agreements.get(position).getAccepted());
//holder.checkbox.setFloorUnCheckedColor(agreements.get(position).getRequired()? Color.rgb(255,0,0):Color.rgb(0,255,0) );
holder.checkbox.setOnCheckedChangeListener((buttonView, isChecked) -> agreements.get(holder.getAdapterPosition()).setAccepted(isChecked));
}
#Override
public int getItemCount()
{
return agreements.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder
{
private TextView textAgreementName;
private AppCompatCheckBox checkbox;
public ViewHolder(View v)
{
super(v);
//textAgreementName = v.findViewById(R.id.text_agreement_name);
checkbox = v.findViewById(R.id.checkbox_agreement_accepted);
}
public void bindData(Agreement agreement)
{
//checkbox.setFloorUnCheckedColor(agreement.getRequired()? Color.rgb(255,0,0):Color.rgb(0,0,255) );
/*if(agreement.getRequired())
{
textAgreementName.setTypeface(null, Typeface.BOLD);
textAgreementName.setText(agreement.getName() + " *");
}
else
textAgreementName.setText(agreement.getName());*/
if(agreement.getRequired())
{
checkbox.setText(agreement.getName() + " *");
checkbox.setTypeface(null, Typeface.BOLD);
}
else
{
checkbox.setText(agreement.getName());
}
}
}
}
All is fine, activity with list shows itself without any problems. Now, I want to use AlertDialog, not activity to display agreements list. I'm trying to create AlertDialog this way (in main activity):
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = inflater.inflate(R.layout.activity_agreements, null);
alertDialog.setView(convertView);
RecyclerView list = convertView.findViewById(R.id.list);
list.setLayoutManager(new LinearLayoutManager(this));
list.setHasFixedSize(true);
AgreementsAdapter adapter = new AgreementsAdapter(agreements);
list.setAdapter(adapter);
alertDialog.show();
agreements variable contains agreements list (the same as previously passed to AgrrementsActivity). But it does not work - dialog is shown with custom layout, but list is always empty.
Can anybody point me what am I missing?
New code with fixed size and other suggestions:
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = inflater.inflate(R.layout.activity_agreements, null);
RecyclerView list = convertView.findViewById(R.id.list);
list.setLayoutManager(new LinearLayoutManager(this));
list.setHasFixedSize(true);
AgreementsAdapter adapter = new AgreementsAdapter(agreements);
list.setAdapter(adapter);
alertDialog.setView(convertView);
AlertDialog dialog = alertDialog.create();
dialog.getWindow().setLayout(600, 400);
dialog.show();
adapter.notifyDataSetChanged();
Your RecyclerView is probably showing the list, but it has a height of 0 so it looks empty.
Dialog size is kind of tricky, check this answer and try to give it a fixed height (maybe a percent of your screen height).
I know it is very late to answer this question but I have also faced the same issue. So for the people who is still facing this issue can use below technique.
If you are using Recycler View with constraint layout and have set the layout_height="0" in alert dialog then u will not be able to see the recycler View list. to resolve this issue set this
app:layout_constraintHeight_default="wrap"
in recyclerview
after hours looking for the best way to use RecyclerView and AlertDialog and ConstraintLayout, solution:
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/abc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintHeight_default="wrap"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/abc" />
<ProgressBar
android:id="#+id/progressBarFavorito"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/abc" />
</androidx.constraintlayout.widget.ConstraintLayout>
for Using recyclerview in alertdialogue,u should be a bit tricky.As u use match parent,so width of recyclerview is 0 because recyclerviews dimension is set before alertdialogue is created.So you do such:
1)use runnable and set your adapter (or other activities we do with recyclerview) 1 sec delaying
or,
2)when you initialize recyclerview,then just set it's layoutparams programmactically. This solved my issue.(don't use this code blindly,i just copied it from my codes,and it may not be suitable for your one.rather just get idea about the issue.)
member_list.setLayoutParams(new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
The problem is getView method does not get called even when I do setAdapter on listView. Please see may code below. I dont get any error message. It just does not display reviewer data. Would you please suggest what I am doing incorrect.
MovieReviewerFragmemt class I have below code:
#Override
protected void onPostExecute (ArrayList movieDetailsArray){
getMovieArrayList(movieDetailsArray);
ListView listView = (ListView) rootView.findViewById(R.id.movie_detail_reviewerlist);
MovieAddlDetail detail = (MovieAddlDetail) movieDetailsArray.get(0);
MovieReviewers[] list = detail.getReviewerArrayList();
Log.v(LOG_TAG, "MovieReviewerFragment - CustomReviewerAdapter - calling adapter");
movieDetailAdapter = new CustomReviewerAdapter(getActivity(), list);
movieDetailAdapter.notifyDataSetChanged();
listView.setAdapter(movieDetailAdapter);
}
CustomerReviewAdapter:
public class CustomReviewerAdapter extends ArrayAdapter {
private Context context;
private LayoutInflater inflater;
private final String LOG_TAG1 = CustomReviewerAdapter.class.getSimpleName();
private MovieReviewers[] reviewers;
public CustomReviewerAdapter(Context context, MovieReviewers[] reviewers) {
super(context, R.layout.fragment_detail, reviewers);
Log.v(LOG_TAG1, "CustomReviewerAdapter - constructor");
this.context = context;
this.reviewers = reviewers;
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.v(LOG_TAG1, "CustomReviewerAdapter - getView");
if (convertView == null) {
inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.fragment_detail_reviewer, parent, false);
Log.v(LOG_TAG1, "CustomReviewerAdapter - getView - convertview was null");
}
TextView textView1 = (TextView) convertView.findViewById(R.id.movie_detail_reviewerlist_author);
TextView textView2 = (TextView) convertView.findViewById(R.id.movie_detail_reviewerlist_content);
textView1.setText(reviewers[position].getAuthor());
textView2.setText(reviewers[position].getContent());
Log.v(LOG_TAG1, "CustomReviewerAdapter - getView - data set");
return convertView;
}
}
Fragment Detail Reviewer:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id ="#+id/imageView_layout"
android:orientation = "vertical">
<TextView
android:layout_width="match_parent" android:layout_height="wrap_content"
android:id="#+id/movie_detail_reviewerlist_author"
android:textAlignment="center"
android:textStyle="bold"
android:gravity="center_vertical"
android:focusable="false"
android:focusableInTouchMode="false"
android:textAppearance="?android:attr/textAppearanceLarge"
android:descendantFocusability="blocksDescendants"/>
<TextView
android:layout_width="match_parent" android:layout_height="wrap_content"
android:id="#+id/movie_detail_reviewerlist_content"
android:textAlignment="center"
android:textStyle="bold"
android:gravity="center_vertical"
android:focusable="false"
android:focusableInTouchMode="false"
android:textAppearance="?android:attr/textAppearanceLarge"
android:descendantFocusability="blocksDescendants"/>
Fragment Detail:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/movie_detail_list"
android:editable="false" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/movie_detail_reviewerlist"
android:editable="false" />
Below is activity from which fragment is being initiated. The first fragment is working fine and is being displayed. However the second fragment is where I dont get anything displayed. Is below correct way to initiate two fragments?
Detail Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Bundle extras = getIntent().getExtras();
intentData = extras.getStringArray("moviedetails");
MovieDetailFragment movieDetailFragment = new MovieDetailFragment();
movieDetailFragment.setMovieDetails(intentData);
MovieReviewerFragment movieReviewerFragment = new MovieReviewerFragment();
movieReviewerFragment.setMovieDetails(intentData);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container_1, movieDetailFragment)
.add(R.id.container_2, movieReviewerFragment)
.commit();
}
}
You must call the LayoutInflater like this:
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
You have to switch the lines
movieDetailAdapter.notifyDataSetChanged();
listView.setAdapter(movieDetailAdapter);
To
listView.setAdapter(movieDetailAdapter);
movieDetailAdapter.notifyDataSetChanged();
First you set the adapter, then you send the notification. If you do this the reverse way, there is no ListView which may display the updated data.
You can automate these notifications with
movieDetailAdapter.setNotifyOnChange(true)
I have a problem with a Fragment.
There is a Dialog inside a Fragment, and a Fragment inside this Dialog.
But when I add the second Fragment, there is an IllegalArgumentException : No view found for id ***** (fr.*****:id/container_list_collections) for fragment FragmentCollectionVignette.
FragmentHP.java
public class FragmentHP extends Fragment {
/** Bouton Ajouter à **/
private Button btAddTo;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
View vueFragmentHP = inflater.inflate(R.layout.fragment_hp, container, false);
getFragmentManager().beginTransaction().replace(R.id.container_dernier_ajout, new FragmentDerniersAjoutsHP()).commit();
getFragmentManager().beginTransaction().replace(R.id.container_collections, new FragmentCollectionsHP()).commit();
getFragmentManager().beginTransaction().replace(R.id.container_ebooks, new FragmentEbooksHP()).commit();
getFragmentManager().beginTransaction().replace(R.id.container_games, new FragmentGamesHP()).commit();
getFragmentManager().beginTransaction().replace(R.id.container_software, new FragmentSoftwareHP()).commit();
getFragmentManager().beginTransaction().replace(R.id.container_digital_creation, new FragmentDigitalCreationHP()).commit();
btAddTo = (Button) vueFragmentHP.findViewById(R.id.bt_collections);
btAddTo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_add_to, null);
final Dialog dialog = new Dialog(getActivity());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(view);
dialog.show();
dialog.setCanceledOnTouchOutside(false);
Button btValider = (Button) view.findViewById(R.id.bt_add_to);
getFragmentManager().beginTransaction().add(R.id.container_list_collections, new FragmentCollectionVignette()).commit();
}
});
return vueFragmentHP;
}
}
dialog_add_to.xml
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/tv_add_to"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/add_to"/>
<TextView
android:id="#+id/tv_choose_collection"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/choose_collection"
android:layout_below="#id/tv_add_to"/>
<FrameLayout
android:id="#+id/container_list_collections"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/tv_choose_collection"/>
<Button
android:id="#+id/bt_add_to"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/valider"
android:layout_below="#id/container_list_collections"/>
</RelativeLayout>
What is the problem ?
(Sorry for my very bad english)
i think the problem is in this line
getFragmentManager()
.beginTransaction()
.add(R.id.container_list_collections, new FragmentCollectionVignette())
.commit();
change this to
this.getActivity()
.getFragmentManager()
.beginTransaction()
.add(R.id.container_list_collections, new FragmentCollectionVignette())
.commit()
I have one activity that contains text view, buttons, spinner and list view
my main XML file contains :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffff00"
tools:context="com.example.taxitabriz.MainActivity"
tools:ignore="MergeRootFrame" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="8dp"
android:text="#string/app_name"
android:textSize="35dp"
android:textStyle="bold"
android:textColor="#996600"
android:textAppearance="?android:attr/textAppearanceLarge" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:id="#+id/linearlayout1" >
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#996600"
android:text="#string/exit"
android:background="#drawable/backbutton" />
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#996600"
android:text="#string/about"
android:background="#drawable/backbutton" />
</LinearLayout>
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="19dp" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/spinner1"
android:layout_above="#+id/linearlayout1"
android:layout_alignParentRight="true"
android:layout_weight="49.94" >
</ListView>
and part of my java code is here:
ArrayAdapter<String> ard=new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line,s1);
sp.setAdapter(ard);
lv1=(ListView) findViewById(R.id.listView1);
ArrayAdapter<String> ard1=new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line,s1);
lv1.setAdapter(ard1);
but i can't change font color or font type in list view or spinner. how can i do it?
You need to create a CustomListAdapter.
private class CustomListAdapter extends ArrayAdapter {
private Context mContext;
private int id;
private List <String>items ;
public CustomListAdapter(Context context, int textViewResourceId , List<String> list )
{
super(context, textViewResourceId, list);
mContext = context;
id = textViewResourceId;
items = list ;
}
#Override
public View getView(int position, View v, ViewGroup parent)
{
View mView = v ;
if(mView == null){
LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = vi.inflate(id, null);
}
TextView text = (TextView) mView.findViewById(R.id.textView);
if(items.get(position) != null )
{
text.setTextColor(Color.WHITE);
text.setText(items.get(position));
text.setBackgroundColor(Color.RED);
int color = Color.argb( 200, 255, 64, 64 );
text.setBackgroundColor( color );
}
return mView;
}
}
The list item looks like this (custom_list.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:textSize="20px" android:paddingTop="10dip" android:paddingBottom="10dip"/>
</LinearLayout>
Use the TextView api's to decorate your text to your liking
and you will be using it like this
listAdapter = new CustomListAdapter(YourActivity.this , R.layout.custom_list , mList);
mListView.setAdapter(listAdapter);
If you really want to use androids simple list layout, we see that they declare their textview's identifier as such:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
style="?android:attr/dropDownItemStyle"
android:textAppearance="?android:attr/textAppearanceLargeInverse"
android:singleLine="true"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:ellipsize="marquee" />
So just make your custom adapter, inflate their layout & find that text view's id. Something like the following:
public final class CustomAdapter extends ArrayAdapter<String> {
private Context context;
ViewHolder holder;
private ArrayList<String> messages;
public CustomAdapter(Context context, ArrayList<String> data) {
this.context = context;
this.messages = data;
Log.d("ChatAdapter", "called constructor");
}
public int getCount() {
return messages.size();
}
public View getView(int position, View convertView, ViewGroup viewGroup) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.simple_dropdown_item_1line, null);
holder = new ViewHolder();
holder.message = (TextView) convertView
.findViewById(R.id.text1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.message.setText(data.get(position));
holder.message.setTextColor(Color.BLUE);
// don't do this, remember the face variable once just showing explicitly for u
Typeface face=Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf");
holder.message.setTypeface(face);
return convertView;
}
public static class ViewHolder {
public TextView message;
}
}
Edit: The following is how you would use the custom array adapter in your activity.
// I'm not sure if your sp or lv1 wants the adapter, but
// whatever you require your list view's data to be just
// set the custom adapter to it
CustomAdapter<String> myAdapter = new ArrayAdapter<String>(this, s1);
lv1=(ListView) findViewById(R.id.listView1)
lv1.setAdapter(myAdapter);
You can do like this, add a ListView item in xml,at res/layout/list_item1.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#0000ff"
android:testStyle="italic"
android:gravity="center_vertical"
android:paddingLeft="6dip"
android:minHeight="?android:attr/listPreferredItemHeight"
/>
then,
ArrayAdapter<String> ard=new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line,s1);
sp.setAdapter(ard);
lv1=(ListView) findViewById(R.id.listView1);
ArrayAdapter<String> ard1=new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line,s1);// **change R.layout.list_item1**
lv1.setAdapter(ard1);
You have to put the .ttf file of font(which you want to add ) in asstes/fonts/ folder and write code in onCreate method like below. i have puted Chalkduster.ttf in my asstes/fonts/ folder
TextView txttest = (TextView) findViewById(R.id.txttest);
Typeface custom_font = Typeface.createFromAsset(getAssets(),
"fonts/Chalkduster.ttf");
txttest.setTypeface(custom_font);
You can handle clicks of selected item by write code just like below
ListView lvNews = (ListView) findViewById(R.id.lvNews);
lvNews.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// Write your code here
//int newsId = newsArray.get(position).getId();
//Intent i = new Intent(NewsListActivity.this,
// NewsDetailActivity.class);
//i.putExtra(Constants.NEWS_ID, newsId);
//i.putExtra("isFromNotification", false);
//startActivity(i);
}
});
I test my application on debug and crash on this line:
listAdapter = new ArrayAdapter<String>(this, R.layout.cd_edittext_for_listview, planetList);
with this error:
System services not available to Activities before onCreate()
I solved this error whit this code (change this with context):
listAdapter = new ArrayAdapter(promptsView.getContext(), R.layout.cd_edittext_for_listview, planetList);
And change on XML file "EditView" with "EditText"!*
I have this layout for the items "editText_for_listview.xml":
<EditView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rowEditView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp">
</EditView>
And my main layout "items_listview.xml"
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="10dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<ListView
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/mylistview"
android:layout_gravity="center" />
</LinearLayout>
The code is this:
public void _ShowItems(String sTitle,android.content.Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(sTitle);
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
final View promptsView = inflater.inflate(R.layout.items_listview, null);
ListView mainListView ;
ArrayAdapter<String> listAdapter ;
mainListView = (ListView) promptsView.findViewById( R.id.editText_for_listview );
String[] planets = new String[] { "Test1", "Test2", "Test3" };
ArrayList<String> planetList = new ArrayList<String>();
planetList.addAll( Arrays.asList(planets) );
listAdapter = new ArrayAdapter<String>(this, R.layout.cd_edittext_for_listview, planetList);
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter( listAdapter );
builder.setView(promptsView)
.setPositiveButton("One", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Two", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.show();
}
Can you help me?
Where I wrong?
Thanks
Obviously you are trying to use the Activity Context prior to the Activity's onCreate() method being called. Try moving your call to _ShowItems() to onResume() method.
Could you show up more code of your activity. You could just be calling the method in a spot where the context isn't initialized but something else could be going on that will be revealed once we have a better look at the activity.
I would have made this a comment but I don't have the reputation to do so.