首页 > 解决方案 > 在 alertdialog 中添加 textview 边距/填充

问题描述

我正在尝试在 alertdialog 中为我的 textview 添加边距。

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);

但仍然没有帮助,那么如何为我的 textview 添加边距?

标签: androidandroid-alertdialog

解决方案


试试这个。当你添加一个 textView 所以你不需要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是您使用警报对话框的活动的上下文。因此,请确保活动应具有主题 Theme.AppCompat。或者您可以更改应用程序的样式。

例如:

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在当前活动或活动中的后续片段中用作上下文。


推荐阅读