#android #kotlin #android-gridview
#Android #kotlin #android-gridview
Вопрос:
У меня есть пример приложения для Android в Kotlin. В моей activity у меня есть изображения, отображаемые в gridview, и я хочу, чтобы они случайным образом исчезали (или менялись на какое-то другое изображение), но я не могу понять, где написать этот код, потому что OnStart или onResume не сработали для меня.
Вот мой код:
class GameActivity : AppCompatActivity()
{
private var settings: Settings = Settings(1, 2, 2, 2)
private var _settingsRepository: SettingsRepository? = null;
private var _handler: Handler = Handler()
private var _runnable: Runnable = Runnable { }
private var counter: Int = 0
private var _adapter: GridElementAdapter? = null;
private var _gridElementList: List<Item> = ArrayList<Item>()
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_game)
_settingsRepository = SettingsRepository(this.applicationContext)
settings = _settingsRepository!!.read()
gridView.numColumns = settings.column
gridView.setExpanded(true)
val windowSize: Size = getGridSize()
_gridElementList = getData()
_adapter = GridElementAdapter(this, _gridElementList, settings, windowSize)
gridView.adapter = _adapter;
}
override fun onStart()
{
super.onStart()
hideElements()
startCounter()
}
private fun hideElements()
{
if(gridView.adapter.count == 0)
{
return
}
var hideOrdder: ArrayList<Int> = ArrayList<Int>()
for (i in 0 until gridView.adapter.count)
{
hideOrdder.add(i)
}
hideOrdder.shuffle()
for (i in hideOrdder)
{
try
{
var gridChild: Item = gridView.adapter.getItem(i) as Item
val element: Drawable? = getDrawable(gridChild.drawableId)
Thread.sleep((settings!!.speed * 100).toLong())
}
catch (e:Exception)
{
print(e.localizedMessage)
}
}
}
private fun getData() : List<Item>
{
var gridElements: ArrayList<Item> = ArrayList<Item>()
gridElements.add(Item("11", R.drawable.makk_asz))
gridElements.add(Item("12", R.drawable.makk_kiraly))
gridElements.add(Item("13", R.drawable.makk_felso))
gridElements.add(Item("14", R.drawable.makk_also))
gridElements.add(Item("15", R.drawable.makk_tizes))
gridElements.add(Item("16", R.drawable.makk_kilences))
gridElements.add(Item("17", R.drawable.makk_nyolcas))
gridElements.add(Item("18", R.drawable.makk_hetes))
gridElements.add(Item("21", R.drawable.piros_asz))
gridElements.add(Item("22", R.drawable.piros_kiraly))
gridElements.add(Item("23", R.drawable.piros_felso))
gridElements.add(Item("24", R.drawable.piros_also))
gridElements.add(Item("25", R.drawable.piros_tizes))
gridElements.add(Item("26", R.drawable.piros_kilences))
gridElements.add(Item("27", R.drawable.piros_nyolcas))
gridElements.add(Item("28", R.drawable.piros_hetes))
gridElements.add(Item("31", R.drawable.zold_asz))
gridElements.add(Item("31", R.drawable.zold_kiraly))
gridElements.add(Item("33", R.drawable.zold_felso))
gridElements.add(Item("34", R.drawable.zold_also))
gridElements.add(Item("35", R.drawable.zold_tizes))
gridElements.add(Item("36", R.drawable.zold_kilences))
gridElements.add(Item("37", R.drawable.zold_nyolcas))
gridElements.add(Item("38", R.drawable.zold_hetes))
gridElements.add(Item("41", R.drawable.tok_asz))
gridElements.add(Item("42", R.drawable.tok_kiraly))
gridElements.add(Item("43", R.drawable.tok_felso))
gridElements.add(Item("44", R.drawable.tok_also))
gridElements.add(Item("45", R.drawable.tok_tizes))
gridElements.add(Item("46", R.drawable.tok_kilences))
gridElements.add(Item("47", R.drawable.tok_nyolcas))
gridElements.add(Item("48", R.drawable.tok_hetes))
val count: Int = settings.column * settings.row
gridElements.shuffle()
return gridElements.take(count)
}
private fun startCounter()
{
_runnable = object : Runnable
{
override fun run()
{
counter
_handler.postDelayed(this, 1000)
}
}
_handler.post(_runnable)
}
private fun stopCounter()
{
_handler.removeCallbacks(_runnable)
counter = 0
}
private fun getGridSize() : Size
{
val displaymetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displaymetrics);
val screenHeight = displaymetrics.heightPixels
val screenWidth = displaymetrics.widthPixels
val height: Int = ( (screenHeight) / settings!!.row * 0.8).toInt()
val width: Int = ((screenWidth / settings!!.column) * 0.62).toInt()
return Size(width, height)
}
}
class GridElementAdapter: BaseAdapter
{
private var _gridElementList: List<Item> = ArrayList<Item>()
private var _context: Activity? = null
private var _settings: Settings? = null
private var _dimension: Size? = null
private var _loyoutInflater: LayoutInflater? = null
constructor(context: Activity, list: List<Item>, settings: Settings, dimension: Size) : super()
{
_context = context
_gridElementList = list
_settings = settings
_dimension = dimension
_loyoutInflater = LayoutInflater.from(context)
}
override fun getCount(): Int {
return _gridElementList.size
}
override fun getItem(i: Int): Item
{
return _gridElementList[i]
}
override fun getItemId(i: Int): Long
{
return _gridElementList[i].drawableId.toLong()
}
override fun getView(i: Int, view: View?, viewGroup: ViewGroup?): View?
{
var v = view
val picture: ImageView
val name: TextView
if (v == null)
{
v = _loyoutInflater!!.inflate(R.layout.grid_item, viewGroup, false)
v.setTag(R.id.picture, v.findViewById(R.id.picture))
v.setTag(R.id.text, v.findViewById(R.id.text))
v.setId(R.id.text.toInt())
}
picture = v!!.getTag(R.id.picture) as ImageView
name = v!!.getTag(R.id.text) as TextView
val item = getItem(i)
picture.setImageResource(item.drawableId)
name.text = item.name
return v
}
}
class Item
{
var name: String
var drawableId: Int = 0
constructor(name: String, drawableId: Int)
{
this.name = name
this.drawableId = drawableId
}
}
activity_game.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".GameActivity">
<com.memorygame.components.GameGridView
android:id="@ id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center|center_horizontal|fill_horizontal|center_vertical|fill_vertical"
android:horizontalSpacing="2dp"
android:isScrollContainer="false"
android:stretchMode="columnWidth"
android:verticalSpacing="5dp" />
<LinearLayout
android:id="@ id/counterLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_column="2"
android:gravity="bottom"
android:orientation="horizontal"
android:visibility="visible">
<TextView
android:id="@ id/timeLabelTextView"
android:layout_width="301dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="Eltelt idő"
android:textAlignment="center"
android:textSize="24sp" />
<TextView
android:id="@ id/timeTextView"
android:layout_width="168dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="0"
android:textAlignment="center"
android:textSize="24sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
grid_item.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal|fill_horizontal|center_vertical|fill_vertical">
<com.memorygame.components.SquareImageView
android:id="@ id/picture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY" />
<TextView
android:id="@ id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="#55000000"
android:paddingLeft="10dp"
android:paddingTop="15dp"
android:paddingRight="10dp"
android:paddingBottom="15dp"
android:textColor="@android:color/white" />
</FrameLayout>
class GameGridView: GridView
{
private var expanded: Boolean = false
constructor(context: Context?): super(context)
{}
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
{}
constructor(context: Context?, attrs: AttributeSet?, defStyle: Int): super(context, attrs, defStyle)
{}
private fun isExpanded(): Boolean
{
return expanded
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int)
{
// HACK! TAKE THAT ANDROID!
if (isExpanded())
{
// Calculate entire height by providing a very large height hint.
// View.MEASURED_SIZE_MASK represents the largest height possible.
val expandSpec = MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK, AT_MOST)
super.onMeasure(widthMeasureSpec, expandSpec)
val params: ViewGroup.LayoutParams = layoutParams
params.height = measuredHeight
}
else
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
}
fun setExpanded(expanded: Boolean)
{
this.expanded = expanded
}
}
class SquareImageView : androidx.appcompat.widget.AppCompatImageView
{
constructor(context: Context) : super(context) {}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {}
constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) {}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
setMeasuredDimension(measuredWidth, measuredWidth)
}
}
Моя проблема в том, что я не знаю, как скрыть изображения в сетке после инициализации пользовательского интерфейса и что было бы наилучшей практикой.
Ответ №1:
Я рекомендую использовать RecyclerView с. GridLayoutManager
Затем вы можете обновлять элементы с помощью adapter.submitList(items)
.