[Android] How to align listView text center?

How to align listView text center?
hello. I want the text to be centered.

figgg

I want to center the text in each list.
Is there any way?

Source code:

ref : @ EmmanulPil / @noel

  public void onStart() {
  super.onStart();
  act = this.getActivity();
  padding_left = width/6;
  padding_right = width/6;
  padding_bottom = height/6;
  padding_top = height/6;
  ArrayAdapter adapter = new ArrayAdapter<String>(act, android.R.layout.simple_list_item_1, myStringArray);
  listView = new ListView(act);
  listView.setLayoutParams(new RelativeLayout.LayoutParams(width-padding_left-padding_right, height-padding_top-padding_bottom));
  listView.setAdapter(adapter);
  listView.setBackgroundColor(Color.rgb(255, 230, 130));
  listView.setX(padding_left);
  listView.setY(padding_top);
  //listView.setPadding(padding_left, padding_top, padding_right, padding_bottom);
  listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      Object list = listView.getItemAtPosition(position);
      background(255, 190, 10);
      text("You have chosen item:  "+list, width/2, height/2);
      text("Click to call list again.", width/2, height/2+100);
      listView.setVisibility(View.GONE);
    }
  }
  );
  listView.setVisibility(View.GONE);
  fl = (FrameLayout)act.findViewById(R.id.content);
  fl.addView(listView);
}

Hi
Play with this line

//listView.setPadding(padding_left, padding_top, padding_right, padding_bottom);

listView.setPadding(padding_left+100, padding_top, padding_right, padding_bottom);


1 Like

@jafal

Thank you for answer.

But I want the text to be centered.

Add a few imports (could be more, I tried to remember them all):

import android.view.ViewGroup;
import android.widget.TextView;
import android.view.Gravity;

Then change the Adapter:

  ArrayAdapter adapter = new ArrayAdapter<String>(act, android.R.layout.simple_list_item_1, android.R.id.text1, myStringArray) {
    @Override
      public View getView(int position, View convertView, ViewGroup parent) {
      TextView textView = (TextView) super.getView(position, convertView, parent);
      textView.setGravity(Gravity.CENTER_HORIZONTAL);
      return textView;
    }
  };

Basically you have to get the TextView that goes with the ListView and change its Gravity to center the text.

2 Likes

@svan

I solved it thanks to you.
thank you.

textView.setGravity(Gravity.CENTER); // CENTER_HORIZONTAL

1 Like