在AlertDialog中添加TextView边距/填充



我正在尝试在alertdialog中为我的文本视图添加保证金。

AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); 
builder.setTitle(notificationList.get(position).getNotificationTitle());
final TextView tv = new TextView(getContext());
tv.setInputType( InputType.TYPE_CLASS_NUMBER );   
tv.setText(notificationList.get(position).getNotificationMessage());
builder.setView(tv);

我正在尝试将我的脚本更改为此

AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setTitle(notificationList.get(position).getNotificationTitle());
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                params.setMargins(10,10,10,10);
                final TextView tv = new TextView(getContext());
                tv.setLayoutParams(params);
                tv.setInputType( InputType.TYPE_CLASS_NUMBER );
                tv.setText(notificationList.get(position).getNotificationMessage());
                builder.setView(tv);

但仍然没有帮助,那么我该如何将保证金添加到我的文本视图?

尝试这个。当您添加文本视图时,您不需要tv.setInputType(InputType.TYPE_CLASS_NUMBER);

    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
    builder.setTitle((notificationList.get(position).getNotificationTitle());
    final TextView tv = new TextView(mContext);
    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    layoutParams.height = 100;
    layoutParams.width = FrameLayout.MarginLayoutParams.MATCH_PARENT;
    layoutParams.setMargins(50, 20, 50, 10);
    tv.setText(notificationList.get(position).getNotificationMessage());
    tv.setGravity(Gravity.CENTER);
    builder.setView(tv);
    builder.create().show();
    tv.setLayoutParams(layoutParams);

您可以根据需要更改layoutParams.setMargins(int left, int top, int right, int bottom)中的保证金。mContext是您使用"警报"对话框的活动的上下文。因此,请确保活动应该具有主题为主题。或者您可以更改应用程序的样式。

eg:

public class MainActivity extends AppCompatActivity {
    private Context mContext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
    }
}

现在,您可以将mContext用作当前活动或活动后续片段中的上下文。

请尝试以下代码

AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); 
builder.setTitle(notificationList.get(position).getNotificationTitle());
final LinearLayout ll = new LinearLayout(getContext());
ll.removeAllViews();
final TextView tv = new TextView(getContext());
tv.setInputType( InputType.TYPE_CLASS_NUMBER );   
tv.setText(notificationList.get(position).getNotificationMessage());

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                params.setMargins(10,10,10,10);
 tv.setLayoutParams(params);
ll.addView(tv);
builder.setView(ll);

最新更新